首先,看看这张图片
Gmail 使用此图像来显示动画表情符号。
我们如何使用 png 图像来显示这样的动画?
最佳答案
我给你留了一个粗略的example这样你就可以得到一个起点:
我将使用一个简单的 div 元素,以及动画图像将具有的 width
和 height
,png Sprite 作为 background-image
> 和 background-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;
}
需要标记:
<div id="anim"></div>
技巧基本上是使用 background-position
CSS 属性向上滚动背景图像 Sprite 。
我们需要知道动画图像的高度
(以知道每次向上滚动多少)以及滚动多少次(会滚动多少帧)有动画)。
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'))
编辑:您还可以以编程方式设置 CSS 属性,这样您就不必在页面上定义任何样式,并创建 constructor function从上面的示例来看,这将允许您同时显示多个 Sprite 动画:
用法:
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"
});
实现:
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);
};
}
请注意,我添加了一个 stopAnimation
方法,因此您稍后只需调用它即可停止指定的动画,例如:
monkey.stopAnimation();
检查上面的例子here .
关于javascript - 如何使用 javascript 显示 PNG 图像的动画图像? [ 如 Gmail ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1736922/