Javascript animation - Bouncing ball
No tutorial about animation would be complete without a bouncing ball example. For animation to work you need to make use of the built in Javascript timer. The code for this animation is shown below.
Using global variables (i.e. variables specified outside a function) in this way is generally not a good idea; because of possible side effects. A future update of this page should fix this.
The drawing of the ball makes use of the arc method and is straightforward. The animation is started by the event which is triggered when the page has finished loading. I.e.
window.onload = init;
at the bottom of the script. It is at this point the variables of width and height re obtained from the canvas element. Also the line in this function
return setInterval(draw, 30);
starts the timer by calling the draw() function every 30ms. You should experiment with this value, and the values of mx and my, to see what effect they have. Very often you will find values like these are set by trail and error. The is no magic formula, but to minimise the load on the processor, the timing value, specified in the function setInterval(), should be the largest value possible, that will create a visually acceptable animation; and this in turn will depend on the incremental movement between frames. e.g. mx, and my.
The interesting part of this program, is what makes the ball bounce? This is achieved by the following if statements one for the x and another for the y direction. Its been deliberately made quite slow so you can see what's happening at the walls.
The draw function calls two other (sub) functions (or helper functions if you like). The first clears the canvas between each successive call by the timer. Try commenting this out and see what happens. The second actually draws the ball.
if (x + mx + r > width || x + mx - r < 0 )
mx = -mx;
if (y + my + r > height || y + my - r < 0)
my = -my;
In plain words, if the centre of the ball + plus the balls radius, plus the incremental distance to be moved is greater than the width of the canvas (e.g. right hand side in x direction), then reverse direction. OR (||) if the centre of the ball - radius + the incremental distance is less than 0 (the left hand side in the x direction), also reverse direction. Eg. mx = -mx. For example, if mx = 2 when the ball collides with the right hand wall the value of mx becomes -2. when it eventually collides with the left wall, -2 = -(-2), which gives plus 2. (two minuses equal a plus).
| Attachment | Size |
|---|---|
| bouncingBall.htm | 1.92 KB |

