Online Book Reader

Home Category

HTML, XHTML and CSS All-In-One for Dummies - Andy Harris [190]

By Root 1470 0
the image filename over from the array to the src property of the spriteImage object.

This step causes the given file to display.

spriteImage.src = imgList[frame];

JavaScript is not an ideal animation framework, but it will do. You do get some delays on the first pass while the images load. (Making the images smaller and in the GIF or PNG formats will help with this issue.) Most browsers store images locally, so the images animate smoothly after the first pass.

If you want smoother animation, you can either preload the images or combine all the frames into a single image and simply change what part of the image is displayed.

Even if you don’t like animation, these techniques can be useful. You can use the setInterval() technique for any kind of repetitive code you want, including the dynamic display of menus or other page elements. In fact, before CSS became the preferred technique, most dynamic menus used JavaScript animation.


Preloading Your Images

The image-swapping trick is pretty cool, but it has one problem: It takes some time for all those images to download from the server, but the animation starts immediately. The animation starting before the images are all available can cause the initial animation to look jerky. It would be great if there was some way to preload the images and not start the animation until they were all available.

Yep, there is a way to do that. Take a look at this code:

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

preload.html

src = “freya/kick00.gif”

alt = “kicking sprite” />

Here’s how you preload images:

1. Change the array name to imgFiles.

This is a subtle but important distinction. The array doesn’t represent actual images, but the filenames of the images. You create another array to hold the actual image data.

2. Create an array of images.

JavaScript has a data type designed specifically for holding image data. The images array holds the actual image data (not just filenames, but the actual pictures). The images array should be global.

3. Create a function to populate the images array.

The loadImages() function creates the array of image data. Call loadImages() from init().

4. Build a loop that steps through each element of the imgFiles array.

You build an image object to correspond to each filename, so the length of the two arrays needs to be the same.

5. Build a new image object for each filename.

Use the new Image() construct to build an image object representing the image data associated with a particular file.

6. Attach that image object to the images array.

This array contains all the image data.

7. Modify animate() to read from the images array.

The animate() function reads from the images() array. Because

Return Main Page Previous Page Next Page

®Online Book Reader