idsos00
Joined: 25 Dec 2008 Posts: 3
|
| Posted: Sun Jun 21, 2009 - 11:23 am Post subject: Animation png?? javascript |
|
|
I had three png files, a.png, b.png, and c.png
I want to make these for animation image
How javascript can do it?? |
|
Hawkman
Joined: 12 Jun 2005 Posts: 28 Location: Derby, UK
|
| Posted: Wed Jun 24, 2009 - 8:12 am Post subject: |
|
|
It's straightforward, but requires a bit of code. Basic idea is to use setInterval() to tick through some src attributes for your <img> element. Here's one example (not as short as it could be, so it's easy to understand), with some control functions:
| Code: | // must be a global variable (not declared inside a function)
var animation = new Object();
// call "setupAnimation" once (must be after page has loaded);
// then call "runAnimation" to start animation as required
setupAnimation();
runAnimation();
// call "stopAnimation" to stop and reset, if necessary
//stopAnimation();
function setupAnimation() {
animation.element = document.getElementById("element_id_here");
animation.images = new Array(3);
// preloads images to prevent flicker, and acts as
// our storage for the image sources
for (var i = 0; i < animation.images.length; i++) {
animation.images[i] = new Image();
}
animation.images[0].src = "a.png";
animation.images[1].src = "b.png";
animation.images[2].src = "c.png";
// duration of each image display, in thousandths of a second
animation.duration = 1000;
animation.showing = 0;
animation.element.src = animation.images[0].src;
}
function runAnimation() {
animation.running = setInterval("tickAnimation();", animation.duration);
}
function tickAnimation() {
animation.showing++;
// check for looping
if (animation.showing >= animation.images.length) animation.showing = 0;
// alternatively stop, if you don't want it looping
//if (animation.showing >= animation.images.length) stopAnimation();
animation.element.src = animation.images[animation.showing].src;
}
function stopAnimation() {
clearInterval(animation.running);
animation.showing = 0;
animation.element.src = animation.images[0].src;
} |
If you don't need to control it, you can lose a lot of that. There are also functions for this kind of thing in libraries such as jQuery, which will reduce the amount of code you need to write; but for a single use it's probably not worth it.
You could adapt this to use the pngs as background images for a <div>, or use an image map, or whatever. Hope this is helpful. |
|