In order to perform an animation in a canvas, we need to:
Clear the content of the canvas: this can be done using the ctx.clearRect(0, 0, canvasWidth, canvasHeight) method;
Draw some shapes: use any of the drawing methods we have seen so far;
Move the shapes: modify the position and/or orientation, size and color of the shapes;
Repeat (go to step 1).
These are the basic steps for animating objects in a canvas. The order of the steps can be changed (i.e. you can move the shapes before drawing them), but, the principle is the same: clear-draw-move-repeat.
Step 1 can be avoided if you redraw the whole canvas content during step 2.
Even before HTML5 and the introduction of the canvas element, people created HTML games. They used CSS backgrounds inside <div> elements, and used to change the CSS top, left, width and height properties of the divs to animate graphic images on the screen.
During the late 1990s and early 2000s, JavaScript became increasingly popular. The community created a first 'umbrella term' describing a collection of technologies used together to create interactive and animated Web sites - DHTML (Dynamic HTML). For example, check the games developed at this time by Brent Silby (they all use DHTML).
For animation, the setInterval(function, ms) and setTimeout(function, ms) methods were the only solutions. Both methods take a function as the first parameter, and a number of milliseconds as the second parameter.
The only difference is that the code provided to setInterval will run every n milliseconds whereas the code in setTimeout will run only once after n milliseconds (meaning that we would have to repeat a call to setTimeout at step 4 above).
The methods described above are now completed by a new method that comes with multiple advantages: the requestAnimationFrame API.
We will compare the old methods with the new one, and implement the sameĀ example with each of them to highlight the differences.