Computer animations are all fake: there is no movement. All that is done is to draw a static image (aka frame), display it for a short while, erase it, draw a slightly modified one, etc.

We've already made a ball, now let's make it move. In order to do so, we'll create a move_ball() function which moves the ball from its current position. We also create an update() function which moves the ball, clear the screeen and draw the ball to its new position, thus giving the illusion of movement. In order to do so, we'll use a call to setTimeout(function, timeout) to call the update() function after starting to run the code, and repeat this at each call for update(). The timeout value has to be specified in milliseconds (ms). We will choose an indirect method by specifying a number of frames per seconds, or FPS, so that the timeout will be given by 1000 ms / FPS.


Additional explanation

You may have noticed that I have also introduced some variables to keep track of the canvas width and height, and use jQuery to obtain these values rather than using some hard coded values. This is because, at some point, I might want to change the canvas size, perhaps because I will want to play this game on a smart phone using a smaller canvas. Regardless of the reason, it is always preferable to either avoid using hard coded values or, if using them, to define them in an easy to find location, like the beginning of a file.

Is there a bug?

Click on the "play" button multiple times. Notice how the ball speeds up. Can you figure out what cause this and fix it before I do in the next section?


Your notebook

Keep your personal notes here. These notes are stored by your browser on your own computer, and will be available from any page on this site. You can choose to use html syntax for formatting.


HTML Add Note


  1. Introduction
  2. Drawing a Ball
  3. Defining Ball Variables
  4. Animate!
  5. Stop!
  6. Pause
  7. Bounce!
  8. Bouncing correctly
  9. Adding a paddle