Monday, February 2, 2015

Javascript Bouncing Ball Example

Link - http://www.sislands.com/coin70/week3/bball.htm


This script uses a the setTimeout() Method to perform a sequence of Image Swaps that create the animation.
The setTimeout() Method accepts two arguments, the name of a Function that you want to call and the number of milliseconds you want to wait before calling the Function. The name of the Function needs to be in "quotes", so it looks like this:
setTimeout("someFunction()", 100);
This example waits 100 milliseconds (one tenth of a second) and then calls "someFunction()".
So, this animation is composed of 5 different images of the ball dropping. Each image is about 300 pixels tall, which is the length that the ball drops. In other words, the image never changes position or size, the ball just changes location in each successive image.
As is the standard when doing an image swap, all five of the ball images are Pre-loaded into Image Objects. In this case, each of the image Objects is also loaded into an Array, which makes it easy to refer to them in the script. This process of Pre-loading the image works like this:
var imageArray = new Array();
imageArray[0] = new Image();
imageArray[0].src = "images/ball0.gif";
imageArray[1] = new Image();
imageArray[1].src = "images/ball1.gif";
etc.
To make the ball drop, there is a Function called bounce() which contains a series of setTimeout() Methods that call each of the five images as the ball drops and then calls each of the five images in reverse order as the ball bounces back up. The setTimeout() Methods have longer and longer time intervals specified. The whole series looks like this:
function bounce() {
     setTimeout("document.images['ball'].src = imageArray[0].src", 100);
     setTimeout("document.images['ball'].src = imageArray[1].src", 200);
     setTimeout("document.images['ball'].src = imageArray[2].src", 300);
     setTimeout("document.images['ball'].src = imageArray[3].src", 400);
     setTimeout("document.images['ball'].src = imageArray[4].src", 500);
     setTimeout("document.images['ball'].src = imageArray[5].src", 600);
     setTimeout("document.images['ball'].src = imageArray[4].src", 700);
     setTimeout("document.images['ball'].src = imageArray[3].src", 800);
     setTimeout("document.images['ball'].src = imageArray[2].src", 900);
     setTimeout("document.images['ball'].src = imageArray[1].src", 1000);
     setTimeout("document.images['ball'].src = imageArray[0].src", 1100);
}
This Function takes almost no time to finish, all of the setTimeout() Methods themselves are executed in less than 15 milliseconds. But the commands that they call, which are all image swaps, occur over a 1.1 second time interval because the setTimeout() Methods have specified it that way.
As we'll see in a later class, it's not good to call more than 20 setTimeout Methods at once. It swamps JavaScript and you'll get an error message.

No comments:

Post a Comment