HTML, XHTML and CSS All-In-One for Dummies - Andy Harris [189]
♦ Put animation images in a subdirectory. With ordinary page images, I often find a subdirectory to be unhelpful. When you start building animations, you can easily have a lot of little images running around. A large number of small files is a good place for a subdirectory.
Building the page
The code for animation just uses variations of techniques described throughout this chapter: a setInterval function and some DOM coding.
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
src = ”freya/kick00.gif”
alt = ”kicking sprite” />
The HTML is incredibly simple:
1. Set up the body with an init() method.
As usual, the body’s onload event calls an init() method to start things up.
2. Create a sprite div.
Build a div named sprite. Because you aren’t changing the position of this div (yet), you don’t need to worry about the local style.
3. Name the img.
In this program, you animate the img inside the div, so you need to give it an id.
Building the global variables
The JavaScript code isn’t too difficult, but it requires a little bit of thought.
1. Create an array of image names.
You have a list of images to work with. The easiest way to support several related images is with an array of image names. Each element of the array is the filename of an image. Put them in the order you want the animation frames to appear.
var imgList = new Array (
“freya/kick00.gif”,
“freya/kick01.gif”,
“freya/kick02.gif”,
“freya/kick03.gif”,
“freya/kick04.gif”,
“freya/kick05.gif”,
“freya/kick06.gif”,
“freya/kick07.gif”,
“freya/kick08.gif”,
“freya/kick09.gif”,
“freya/kick10.gif”,
“freya/kick11.gif”,
“freya/kick12.gif”
);
2. Build a frame variable to hold the current frame number.
Because this animation has 12 frames, the frame variable goes from 0 to 11.
var frame = 0;
3. Set up spriteImage to reference to the img tag inside the sprite tag.
var spriteImage
Setting up the interval
The init() function attaches the spriteImage variable to the image object and sets up the animate() method to run ten times per second.
function init(){
setInterval(“animate()”, 100);
spriteImage = document.getElementById(“image”);
} // end init
Animating the sprite
The actual animation happens in the (you guessed it . . .) animate() function. The function is straightforward:
1. Increment frame.
Add one to the frame variable.
frame += 1;
2. Check for bounds.
Any time you change a variable, you should consider whether it may go out of bounds. I’m using frame as an index in the imgList array, so I check to see that frame is always less than the length of imgList.
if (frame >= imgList.length){
frame = 0;
} // end if
3. Reset frame, if necessary.
If the frame counter gets too high, reset it to zero and start the animation over.
4. Copy