使用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?
只是一个简单的code,它改变成另一种形象,开创了动画的IM pression,就像一个GIF。
Just a simple code that change one image for another, creating the impression of a animation, just like a gif.
我们的想法是使用产生的一面旗帜,所以生病上传的图片(这就是做),我需要一个code这个动画。
The idea is to use for generating a banner, so ill upload the pictures (thats done) and i need a code for this animation.
推荐答案
#1利用这一技术为它的独角兽动画去年愚人节。我preserved在我的网站动画。动画code是我自己 - 我不看计算器是如何做的。
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;
}
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);
}
工作演示: http://jsfiddle.net/twTab/
编辑:如果您不希望创建一个精灵,这里是一个替代技术,您可以使用。把你所有的动画帧图像在一个div和隐藏所有,但第一个。在你的的setInterval
功能,第一个图像移动到列表的末尾:
If you don't want to create a sprite, here's an alternate technique you can use. Put all of your animation frame images in a div and hide all but the first one. In your setInterval
function, move the first image to the end of the list:
#animation img {
display: none;
}
#animation img:first-child {
display: block;
}
<div id="animation">
<img src="charging01.png />
<img src="charging02.png />
<img src="charging03.png />
...
</div>
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屋!