如何使用javascript显示PNG图像的动画图像?[比如gmail]

Rak*_*yal 26 javascript animation png image

首先,看看这个图像
眨眼
Gmail使用此图片显示动画表情符号.
我们如何使用png图像显示这样的动画?

CMS*_*CMS 69

我给你一个粗略的例子,你可以得到一个起点:

我将使用一个简单的div元素,与widthheight该动画形象会有时,PNG精灵作为background-imagebackground-repeat设置no-repeat

CSS需要:

#anim {
  width: 14px; height: 14px;
  background-image: url(https://ssl.gstatic.com/ui/v1/icons/mail/im/emotisprites/wink2.png);
  background-repeat: no-repeat; 
}
Run Code Online (Sandbox Code Playgroud)

标记需要:

<div id="anim"></div>
Run Code Online (Sandbox Code Playgroud)

诀窍基本上是使用background-positionCSS属性滚动背景图像精灵.

我们需要知道height动画图像(知道我们每次会向上滚动多少)以及滚动多少次(动画有多少).

JavaScript实现:

var scrollUp = (function () {
  var timerId; // stored timer in case you want to use clearInterval later

  return function (height, times, element) {
    var i = 0; // a simple counter
    timerId = setInterval(function () {
      if (i > times) // if the last frame is reached, set counter to zero
        i = 0;
      element.style.backgroundPosition = "0px -" + i * height + 'px'; //scroll up
      i++;
    }, 100); // every 100 milliseconds
  };
})();

// start animation:
scrollUp(14, 42, document.getElementById('anim'))
Run Code Online (Sandbox Code Playgroud)

编辑:您还可以以编程方式设置CSS属性,这样您就不必在页面上定义任何样式,并从上面的示例中创建构造函数,这将允许您同时显示多个精灵动画:

用法:

var wink = new SpriteAnim({
  width: 14,
  height: 14,
  frames: 42,
  sprite: "https://ssl.gstatic.com/ui/v1/icons/mail/im/emotisprites/wink2.png",
  elementId : "anim1"
});

var monkey = new SpriteAnim({
  width: 18,
  height: 14,
  frames: 90,
  sprite: "https://ssl.gstatic.com/ui/v1/icons/mail/im/emotisprites/monkey1.png",
  elementId : "anim4"
});
Run Code Online (Sandbox Code Playgroud)

执行:

function SpriteAnim (options) {
  var timerId, i = 0,
      element = document.getElementById(options.elementId);

  element.style.width = options.width + "px";
  element.style.height = options.height + "px";
  element.style.backgroundRepeat = "no-repeat";
  element.style.backgroundImage = "url(" + options.sprite + ")";

  timerId = setInterval(function () {
    if (i >= options.frames) {
      i = 0;
    }
    element.style.backgroundPosition = "0px -" + i * options.height + "px";
     i++;
  }, 100);

  this.stopAnimation = function () {
    clearInterval(timerId);
  };
}
Run Code Online (Sandbox Code Playgroud)

请注意,我添加了一个stopAnimation方法,因此您可以稍后通过调用它来停止指定的动画,例如:

monkey.stopAnimation();
Run Code Online (Sandbox Code Playgroud)

这里查看上面的例子.

  • +1对于一个相当简单的问题最深入的回答之一 (8认同)