JS实现图片旋转动画效果封装与使用示例

往前走,一片诱人的新绿尽收眼底,那是满池的新荷。荷叶有的平展着圆盘浮在水面上;有的绿伞般在空中摇曳;有的兜着水珠把阳光反射得灿烂夺目;有的长得非常高,却未展开叶面,勇敢地挺立着。荷花则多半含苞待放,白中透粉的一朵朵花儿,活像一个个花仙子借着微风,在池中裙袂飞扬,翩然起舞。

本文实例讲述了JS实现图片旋转动画效果封装与使用。分享给大家供大家参考,具体如下:

核心封装代码如下:

//图片动画封装
function SearchAnim(opts) {
    for(var i in SearchAnim.DEFAULTS) {
      if (opts[i] === undefined) {
        opts[i] = SearchAnim.DEFAULTS[i];
      }
    }
    this.opts = opts;
    this.timer = null;
    this.elem = document.getElementById(opts.elemId);
    this.startAnim();
}
SearchAnim.prototype.startAnim = function () {
    this.stopAnim();
    this.timer = setInterval(() => {
      var startIndex = this.opts.startIndex;
      if (startIndex == 360) {
        this.opts.startIndex = 0;
      }
      this.elem.style.transform = "rotate("+ (startIndex) +"deg)";
      this.opts.startIndex += 5;
    }, this.opts.delay);
    setTimeout(() => {
      this.stopAnim();
    }, this.opts.duration);
}
SearchAnim.prototype.stopAnim = function() {
    if (this.timer != null) {
      clearInterval(this.timer);
    }
}
SearchAnim.DEFAULTS = {
    duration : 60000,
    delay : 200,
    direction : true,
    startIndex : 0,
    endIndex : 360
}

使用方法:

随便创建一img标签

然后如下调用即可:

new SearchAnim({
  elemId : "wait-icon",
  delay : 20,
});

完整示例代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>www.haodaima.com JS旋转动画</title>
</head>
<img src="https://files.haodaima.com/file_images/article/201807/201879100307926.jpg" id="wait-icon"/>
<script>
//图片动画封装
function SearchAnim(opts) {
    for(var i in SearchAnim.DEFAULTS) {
      if (opts[i] === undefined) {
        opts[i] = SearchAnim.DEFAULTS[i];
      }
    }
    this.opts = opts;
    this.timer = null;
    this.elem = document.getElementById(opts.elemId);
    this.startAnim();
}
SearchAnim.prototype.startAnim = function () {
    this.stopAnim();
    this.timer = setInterval(() => {
      var startIndex = this.opts.startIndex;
      if (startIndex == 360) {
        this.opts.startIndex = 0;
      }
      this.elem.style.transform = "rotate("+ (startIndex) +"deg)";
      this.opts.startIndex += 5;
    }, this.opts.delay);
    setTimeout(() => {
      this.stopAnim();
    }, this.opts.duration);
}
SearchAnim.prototype.stopAnim = function() {
    if (this.timer != null) {
      clearInterval(this.timer);
    }
}
SearchAnim.DEFAULTS = {
    duration : 60000,
    delay : 200,
    direction : true,
    startIndex : 0,
    endIndex : 360
}
new SearchAnim({
  elemId : "wait-icon",
  delay : 20,
});
</script>
<body>
</body>
</html>

使用本站HTML/CSS/JS在线运行测试工具:http://tools.haodaima.com/code/HtmlJsRun,可得到如下测试运行效果:

希望本文所述对大家JavaScript程序设计有所帮助。

以上就是JS实现图片旋转动画效果封装与使用示例。有时候,我们必须闭上嘴,放下自己的骄傲,承认是自己错了。这不是认输,而是成长。更多关于JS实现图片旋转动画效果封装与使用示例请关注haodaima.com其它相关文章!

标签: JS