Use these to jump around or read it all
The Concept
The Script
The Script’s Effect
Deconstructing the Script
What You’ve Learned
Your Assignment
![]()
The Concept
This example uses JavaScript to create an animation. Here it becomes more important to preload pictures. Remember how to do that? You set them aside, outside a function,
using the new Image() and img.src commands. You’ll see the format below again or maybe you’ll want to jump back one Primer to 27 to see the format.
If the images are not preloaded, the user would have to wait for each picture to be downloaded from a server the first time they are accessed. This would distort the animation!
The Script
<HTML>
<HEAD>
<SCRIPT type="text/javascript">
var num=1
img1 = new Image (150,150)
img1.src = "pic1.gif"
img2 = new Image (150,150)
img2.src = "pic2.gif"
img3 = new Image (150,150)
img3.src = "pic3.gif"
function startshow()
{
for (i=1; i<20; i=i+1)
{document.mypic.src=eval("img"+num+".src")
for(x=1; x<800; x=x+1)
{}
num=num+1
if(num==4)
{num=1}
}
document.mypic.src=img1.src
}
</SCRIPT>
</HEAD>
<BODY>
<CENTER>
<IMG SRC="pic1.gif" NAME="mypic" BORDER=0 alt="">
<p>
<A HREF="JavaScript:startshow()">
Display animation</a>
</CENTER>
</BODY>
</HTML>
|
The Script’s Effect
Display Animation
(Due to changes in browsers, this script may not run on your MSIE browser.)
Deconstructing the Script
- We’ll start with the preloading of images. Notice it is outside of the function as is the variable num. It looks like this:
<SCRIPT type=”text/javascript”> var num=1 img1 = new Image (150,150) img1.src = “pic1.gif” img2 = new Image (150,150) img2.src = “pic2.gif” img3 = new Image (150,150) img3.src = “pic3.gif”
- Now the function:
function startshow()
{
for (i=1; i<21; i=i+1)
{document.mypic.src=eval("img"+num+".src")
for(x=1; x<800; x=x+1)
{}
num=num+1
if(num==4)
{num=1}
}
document.mypic.src=img1.src
}
</SCRIPT>
slow down the picture switiching, so that the different pictures are actually visible by users!
<IMG SRC=”pic1.gif” NAME=”mypic” BORDER=0 alt=””>
Notice the name of the given is “mypic.” If you look at the hierarchy statements in the script, you’ll see that between document and src.
Once again, the HREF is pointed toward the JavaScript:function
so that all Global Variables are included.
What You Have Learned
Your Assignment
Rewrite the program above. Display pic1.gif first, as in the example above, but put it in
a form. Include a text box where the user enters Slow, Medium, or Fast. The user types one of these to determine the speed of the animation. Make Medium the default. 800 will be fast. 1600 will be medium. 2400 will be slow. Include the “Display Animation” text link to start the animation.
Here’s a possible answer to this assignment
(this will open a new window)
The Concept
The Script
The Script’s Effect
Deconstructing the Script
What You’ve Learned
Your Assignment
On To JavaScript Primer #29