Saturday, March 17, 2012

Animation in JavaScript


Today's post is about the basics of animation in JavaScript. A simple image of a ball is moved around a small area.

Preparing the Images

An image of a football was drawn and rotated three times, giving four separate images.

The image rotated three times gives the impression of "rolling".

Simulating Animation

The effect is known as the Phi Phenomenon, where several stationary images are shown, to give the impression of movement.

Here is a snippet of the JavaScript code:

var ball = new Array(4);
var curPos = 0;
var startRolling;

// assigning ball0.png to ball[0], 
// ball3.png to ball[3], etc
for (i=0; i < ball.length; i++) {
 ball[i] = "ball"+i+".png";

function roll() {
 if (curPos == (ball.length-1)){
  curPos = 0;
 } else {
 // change image src to current image, 
 // e.g. ball[2].png
 document.animatedBall.src = ball[curPos];



Additionally, the image of the ball will move horizontally across the screen, giving the user the impression that it is "rolling".

Once the ball reaches an arbitrary point, say, 500 pixels across the screen, it will move backwards (i.e. left). When the ball gets back to the starting position, it wil move forwards again (right).


The easiest way to display JavaScript animation in action is to show you. You can click here, or the big button below:

Note: Google Chrome seems to have some issues smoothly displaying the animation. You might want to view this page on either Safari, Internet Explorer, or Firefox.

Download Source Code

I've made the source code available at this Pastebin, where you can easily view and download my source code.

It's also embedded below.

No comments:

Post a Comment