带有 Javascript 的动画图像 [英] Animated Image with Javascript
问题描述
有没有办法基于一些 png 或 jpg 使用 javascript 创建类似 gif 的图像?
Is there a way to create a gif like image with javascript based on some png or jpg?
只是一个简单的代码,可以将一个图像更改为另一个图像,从而产生动画效果,就像 gif 一样.
Just a simple code that change one image for another, creating the impression of a animation, just like a gif.
这个想法是用来生成横幅的,所以我上传了图片(完成了),我需要这个动画的代码.
The idea is to use for generating a banner, so ill upload the pictures (thats done) and i need a code for this animation.
推荐答案
Stackoverflow 在去年愚人节将这种技术用于其独角兽动画.我在我的网站上
(来源:jumpingfishes.com)
Stackoverflow used this technique for its unicorn animations last april fools day. I preserved the animations on my website. The animation code is my own - I didn't look at how stackoverflow was doing it.
The concept is to create a sprite, and then change the background position on an interval.
#animation {
background-image: url(charging.png);
background-repeat: no-repeat;
height: 102px;
width: 140px;
}
工作演示: http://jsfiddle.net/twTab/
编辑:如果您不想创建精灵,可以使用以下替代技术.将所有动画帧图像放在一个 div 中并隐藏除第一个之外的所有图像.在您的 setInterval
函数中,将第一张图片移动到列表的末尾:
function startAnimation() {
var frameHeight = 102;
var frames = 15;
var frame = 0;
var div = document.getElementById("animation");
setInterval(function () {
var frameOffset = (++frame % frames) * -frameHeight;
div.style.backgroundPosition = "0px " + frameOffset + "px";
}, 100);
}
Working demo: http://jsfiddle.net/twTab/
#animation img {
display: none;
}
#animation img:first-child {
display: block;
}
function startAnimation() {
var frames = document.getElementById("animation").children;
var frameCount = frames.length;
var i = 0;
setInterval(function () {
frames[i % frameCount].style.display = "none";
frames[++i % frameCount].style.display = "block";
}, 100);
}
工作演示: http://jsfiddle.net/twTab/3/
这篇关于带有 Javascript 的动画图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!