HTML and CSS Reference
2. Draw new graphics on the canvas.
3. Repeat steps 1 and 2
Drawing on canvas uses the drawing methods covered earlier, but clearing the canvas
introduces a new method: clearRect(x,y,w,h) . This method clears all graphics
from the canvas within a rectangular area. For animations, this would usually mean
clearing the entire canvas area, unless you could reliably know only one portion of the
canvas would be changing throughout the animation.
The global window object contains two methods for repeating a piece of code over
time, as is needed in an animation: setInterval(f,t) and setTimeout(f,t) .
Both of these methods call a custom function ( f ) after a specified interval ( t ). The in-
terval is set in milliseconds, so 1000 would be one second in length. The difference
between the two is setInterval(f,t) runs continuously, while
setTimeout(f,t) executes only once after the set amount of time. We'll use
setInterval(f,t) to create a basic animation engine.
Note Firefox, Chrome, Opera, and Internet Explorer have an experimental method
called requestAnimationFrame() , which is used to tell the web browser to re-
paint the window in order to redraw the frames of an animation. This has advantages
over using the setInterval() method because the animation runs only when
the browser is available, meaning that, for instance, an animation running in a tab
that is hidden will stop because the page is not being shown, saving the computer's
processor from consuming resources unnecessarily. You can find more information
on this method at https://developer.mozilla.org/en/DOM/win-
To create a basic animation engine, the following functions are created:
• init() to set up initial variables and start the animation
• invalidate() to specify that the animation frame needs to be redrawn
• clear() to clear the animation frame
• draw() to draw the animation frame
• update() to update variables used when drawing the animation frame
Put together, the code for a basic animation engine looks like the following, which
will animate two lines across the canvas ( Figure 7-13 ):
// declare global variables