Animating Graphics


document.images["animation"].src = urls[pos]; window.setTimeout("animate(" + (pos + 1) + ");",      500); 

The GIF file format, originally from CompuServe, is the only graphics format that supports animation and is supported by all popular browsers. However, it also has some severe limitations, most annoyingly the 8-bit color palette that allows only 256 colors to be used. So PNG-24 is the way to go, but unfortunately this format does not have animation capabilities.

In this case, JavaScript is the way to go. Changing a graphic is possible as shown in the preceding phrases, and the only ingredient missing is the use of setInterval() or setTimeout(). The following code iterates through an array of images and moves to the next image after 500 milliseconds (half a second) have elapsed:

Animating Through Images (animate.html)

<script language="JavaScript"   type="text/javascript"> var urls; function animate(pos) {   pos %= urls.length;   document.images["animation"].src = urls[pos];   window.setTimeout("animate(" + (pos + 1) + ");",     500); } window.onload = function() {   urls = new Array(     "0.png", "1.png", "2.png", "3.png",     "4.png", "5.png", "6.png");   animate(0); } </script> <img src="/books/3/490/1/html/2/0.png" name="animation" /> 

The animate() function expects one parameter: the position of the next image to show. The list of images to iterate through is saved in a global variable, since setTimeout() cannot use local variables that are not available in the global scope.

With pos %= urls.length, the pointer to the image list is set to the beginning after the last image has been shown, effectively generating an infinite loop. If you want the animation to end after the last image, replace this line with the following code:

if (pos == urls.length) {   return false; } 





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net