HTML and CSS Reference
In-Depth Information
12.6.1 Changing Image Position
In Example 12.12, two stick figures have been scanned into the computer and saved as
.png files. The figures are loaded and alternately displayed on the screen at short intervals
giving the illusion that the stick figure is running.
EXAMPLE 12.12
<html>
<head><title>animation</title>
<script type="text/javascript">
1
var pics;
2
function animate(whichone) {
3
whichone %= pics.length ;
4
document.images["stickman"].src=pics[whichone];
5
window.setTimeout("animate(" + (whichone + 1)+");",500);
}
6
window.onload=function(){
7
pics=new Array( "0.png","1.png","0.png","1.png");
8
animate(0);
}
</script>
</head>
<body bgcolor=lightgreen>
9
<img src="0.png"
name="stickman" />
</body>
</html>
EXPLANATION
1
A global variable called pics is declared, which will be available to all the functions
in this JavaScript code.
2
The function called animate() is called the first time on line 8. The initial value of
pos is 0. On line 5 the window's setTimeout() function calls animate() repeatedly
every .5 sec. Each time animate() is called the whichone value is incremented by 1.
3
The value of whichone is changed each time the function is called by using the
modulus operator. The remainder will be a number between 0 and 4, not includ-
ing 4. This number is used as an index in the pics array to select an image.
4
The source file for the stick man image file changes each time the function is
called, so rapidly that the stick man appears to be running.
5
This is where the timer is set to cause the animation of the stick man.
6, 7, 8
When the page has loaded this anonymous function will create an array of images,
and then call the animate() function on line 2 with an initial value of 0.
9
The initial stick man image is displayed in the document.
 
 
Search WWH ::




Custom Search