Print Article          Return         

Variable Speed Animation
By: Al DiMarzio HB Graphics
Guilford, CT

Animated GIFs add great eye candy to a Web site, but sometimes you might want to change the animation speed to produce different effects. How would you adjust the speed? Create multiple animated GIFs? I think not. However, you could create multiple single-cell images and use JavaScript to control the speed at which they are seen. This article describes just such a course of action.

But first, about eye candy: Like real candy, too much is not good for us or our Web sites.

A Few Words about Images

Images enhance and extend our message in a way that words alone cannot. A good designer uses images that support the message of the Web site and uses them sparingly so their effect is not diluted. An image-cluttered page creates sensory overload and obscures the message of the page and of each individual image.

However, a page without images is bland and unappealing. The challenge is to bring balance and harmony to Web page topography through the use of both words and images that enhance and support the message.

On with the Project

You will notice that in the animation below, each image is not simply a red ball. Instead it is a red ball with two trailing balls, each offset from the original and with reduced opacity. These additional images provide for smoother animation and can be created with a variety of tools. I used Adobe Photoshop(r) to place each ball on a separate layer. I then created the GIFs using three layers at a time. But then I am old fashioned. There are many other great programs that can assist you.

Before getting into the code, you might consider playing with the animation sequences by either clicking on the two upper images or on the "speed bar" next to the bottom image.

Mouse overs - each image will respond at a different speed.



Speed scale - click on [] to change speed.


SLOW []+ []+ []+ []+ []+ []+ []+ [] FAST


To produce this animation, we create a linear sequence of images and control the time delay between each image displayed. As you view the code, which is listed below, you will see that it contains three basic JavaScript functions that:

  1. Set up the variables for the animation
  2. Establish the time delay between images
  3. Establish the animation loop that sequences the images.

Browser interpretation of JavaScript code is usually very tolerant of numeric variables and can accommodate the nuances between a numerical value of 1 and the ASCII character 1. However, the animation loop counter is one of those instances in which we must specifically use a numerical value. Thus, when the ASCII numerical character is passed from the event handler to the JavaScript function, we must convert it to a pure number.

You may have noticed in the above demonstration that activating a second image halts the first image sequence. This is caused by the resetting of the interval timer when the second image is started.

The code below is heavily annotated, so let us continue this discussion via the HTML and JavaScript comment tags. You may cut and paste everything between the "snip" marks into your editor and begin playing on your own.

------------ Begin snip of Web page -------------

<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>

<SCRIPT LANGUAGE="JavaScript">
<!--

/*  Let's start by taking care of the single-cell images.
Place all the images you plan to use in an array. If you use
more than one animation, be sure to keep all images in the proper
sequence because the looping of pictures is linear. There are many ways
to achieve this effect, but using an array allows you to mix images
with different names and file types. Here we simply increment
a number on the image file name. "ball-1" is repeated at the end
of the array to set up the starting image for the next activation.  */

imageName = new Array("ball-1.gif","ball-2.gif","ball-3.gif","ball-4.gif",
"ball-5.gif","ball-6.gif","ball-7.gif","ball-8.gif","ball-9.gif",
"ball-10.gif","ball-11.gif","ball-12.gif","ball-13.gif","ball-14.gif","ball-15.gif",
"ball-1.gif")   //Keep all this array code on one line.

/* We will be passing several variables between the different
functions, so we set them up as global variables here. (Note: A 
variable declared within a function only exists within
that function.)  */
	
var imagedelay, firstimage, lastimage, displayedimage, intervalID, loopcounter;

/*  An onClick or onMouseOver event from the HTML portion 
of the page initiates this function. Its role in life is to set up additional 
parameters.Descriptions of the passed parameters are, in order of appearance:
name of the HTML image object to receive the images 
index of the first image to be shown in the image array 
index of the last image to be shown, and 
the amount of delay between the images.  */
	
function animateImages(displayimagex, firstimagex, lastimagex, imagedelayx) {

   /*  The ParseInt() function is used for older versions 
   of JavaScript, which need to have numbers explicitly 
   stated when used in comparisons such as in the 
   animateLoop() function.  */
		
   lastimage = parseInt(lastimagex)
   loopcounter = parseInt(firstimagex)
	
   /*  You don't need to redefine the following variables. I just 
   did it to be consistent between the passed parameters and 
   those used within the scripts. (Just a holdover from my 
   early engineering days.)  */
	
   displayimage = displayimagex
   imagedelay = imagedelayx
	
   /*  Clear the timer in case an animation 
    is interrupted by another event.  */
   clearInterval(intervalID)

   /* Now we call the timer to start the animation.  */

   animateTimer()
}

/*  The timer repeatedly calls the animateLoop() function 
until such time as the last image in the sequence 
has been played. The "imagedelay" determines the interval
between these repetitions. The "intervalID" is needed to clear the timer.  */
	
function animateTimer()  {
   intervalID = setInterval("animateLoop()",imagedelay)
}
	
/*  Here we loop through the images from the first image 
to the last image specified in the parameters passed by the 
onMouseOver event. After the last image has been displayed, 
the timer routine is canceled by clearing the timer.  */
	
function animateLoop() {
   if (document.images) {
      /* If there are more images we loop. */
      if(loopcounter <= lastimage) {
         var imageSource = imageName[loopcounter];
         document[displayimage].src = imageSource;
         loopcounter++;  }
      else  {
         /* When the sequence is complete, we clear the timer. */
         clearInterval(intervalID)
      }
   }
}

/*  Depending upon your application, you may want to load
your images immediately after the page has finished loading, 
thus avoiding an initial delay in the animation. To preload the 
images, place the onLoad() event handler in the Body tag of the 
page as shown below. Because our images are all sequential,
we use a simple for..next loop to preload the images. 

The number 15 in the for...next loop is the number of
images that are in the array.  */
	
var thisball, i
function preLoadImages()  {
   if (document.images) {
      for (i=1; i<=15; i++) {
         thisball = "img"+i;
         thisball = new Image(147,63);
         thisball.src = "ball-"+i+".gif";
      }
   }
}

// -->
</SCRIPT>

<BODY bgcolor="#ffffff" onLoad="preLoadImages()">

<div align="center">

   <!-- This table serves no purpose other than to 
   put a box around things. -->

<table width="440" border="2" cellspacing="0" cellpadding="10" 
bordercolor="#800000" bgcolor="#ffffff">
<tr>
   <td>

   <b>Mouse overs</b> - each image will respond at 
   a different speed.<br>
   <br>
	
<!-- Now we come to the interesting part. The onMouseOver
event, shown below, causes four parameters to be passed 
to the animateImages() function.

The first parameter is the name of the HTML image object to 
receive the new image. (Many HTML document objects can
be modified by scripts, however they must be "named" in
order to modify them.)

The second parameter specifies which image will be 
the first to appear in the sequence. We do this 
by specifying the index number of the image in the 
imageName array. Remember that arrays start with 
the number 0. 

The third parameter specifies the last image to be 
displayed, also using the index number. 

You can create all kinds of interesting animation 
simply by changing the beginning and ending image 
index numbers. (Note: Because the process is linear, the 
first image index must always be less than the 
last image index).

The last parameter specifies the length of the timer 
in milliseconds. Now you have it. -->
	
   <a href="#" onMouseOver="animateImages('image1','0','15','75')">
   <img name="image1" src="ball-1.gif" width=147 height=63 border=1 
   alt=""></a>

   <!-- Here we do the same thing for the second image
   but with a longer delay -->
	
   <a href="#" onMouseOver="animateImages('image2','0','15','300')">
   <img name="image2" src="ball-1.gif" width=147 height=63 border=1 
   alt=""></a><br>
	
   <br>
	
   <b>Speed scale</b> - click on [] to change speed.<br>
   <br>
	
   <!-- Nothing new here. We substitute the onClick event for
   the onMouseOver event. You can use any JavaScript event
   to initiate the animation.  -->
	
   <img name="image4" src="ball-1.gif" width=147 height=63 border=1 
   alt="" align="left"><br>
   <font face="Arial" size="-1" color="#008000"><b>
   SLOW  
   <a href="#" onClick="animateImages('image4','0','15','400')"
   >[]</a>+<a href="#" onClick="animateImages
   ('image4','0','15','350')">[]</a>+<a href="#" 
   onClick="animateImages('image4','0','15','300')">[]</a>+<
   a href="#" onClick="animateImages('image4','0','15','250')">[]
   </a>+<a href="#" onClick="animateImages('image4','0','15','200')">
   []</a>+<a href="#" onClick="animateImages('image4','0','15','150')">
   []</a>+<a href="#" onClick="animateImages('image4','0','15','100')">
   []</a>+<a href="#" onClick="animateImages('image4','0','15','50')">
   []</a>
   FAST</b></font><br>
   <br>
   <br>

   </td></tr>
</table>

</div>
</BODY>
</HTML>

---------   End snip of Web Page   ----------
Conclusion

Animation is fun and with variable speed animation you can do some interesting things. However, please keep in mind that all Web page elements, text, images, movies, animation, and other gizmos must be in balance and harmony with the message of the Web site.

About the Author

For additional information about the author, please select Author Biography.

Print Article          Return