Stretching Graphics


document.images["bar"].width += 5; 

Sometimes it is not even necessary to create several graphics to build an animation. Sometimes just stretching an image can create a nifty effect. Usually, this does not fare too well on the Web, since only bitmap file formats are supported (except for Flash or SVG, which is not available across browsers in their default setup). Therefore, stretching a graphic instructs the browser to calculate additional image information. Usually, this is done by copying pixels.

In the case of a progress bar, a simple graphic can suffice. In a simple example, use a 1x1-pixel image. If it is used in the HTML page with a width of 20 pixels and a height of 10 pixels, you get a 20x10-pixel image. By animating the width of the image with JavaScript, you can get the impression of a moving progress bar.

The width and height of an image can be accessed from JavaScript using the width and height properties, both readable and writable. The following code moves the progress bar, using a simple 1x1-pixel graphic, black.gif.

An Animated Progress Bar (progress.html)

<script language="JavaScript"   type="text/javascript"> function progress() {   if (document.images["bar"].width < 200) {     document.images["bar"].width += 5;     document.images["bar"].height = 5;   } else {     clearInterval(ID);   }  } var ID; window.onload = function() {   ID = setInterval("progress();", 500); } </script> <img src="/books/3/490/1/html/2/black.gif" name="bar" /> 

Figure 3.2 shows the example in action: The 1x1 image has been stretched dynamically by JavaScript. The progress() function is called every 500 millisecond, thanks to the setInterval() call. After the progess bar has reached its maximum length (in this example, arbitrarily 200 pixels), the animation is stopped with clearInterval().

Figure 3.2. The graphic is animated so that it looks like a progress bar.


Warning

If you do not explicitly set the height of the progress bar image, stretching its width also stretches the height, ruining the desired effect.





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