function init()
{
canvas = document.getElementById('canvas');
context2D = canvas.getContext('2d');
setInterval(draw, 1000 / FPS);
}
Once the page has been loaded the init function is called. Here we can get a reference to the canvas element, referencing it by the ID attribute defined in the HTML file (unimaginatively called canvas here). We also need a reference to the 2D context of the canvas.
The context defines how the canvas is drawn to. As the name suggests, the 2D context allows 2D shapes, images and text to be drawn to the canvas. All browsers that support the canvas element support the 2D context, but there are other experimental contexts available. Opera has a 2D context designed specifically with games in mind, and Mozilla has a 3D context for displaying 3D scenes. Unfortunately these additional contexts are only supported on specific browsers at the moment, so if you want to create a web application that uses the canvas element it's best to stick to the vanilla 2D context.
Because we are drawing an animated image, we need to set up what is called a render loop. A render loop is just a function that is called repeatedly, allowing (in this case) the position of the image to be moved slightly across the screen during each iteration of the render loop, giving the impression of movement. For this we call the setInterval function. The first parameter is the function that should be called, which we have named draw. The second is the frequency that the function is called at. This value is measured in milliseconds, so we divide 1000 by the FPS value defined earlier to calculate how many milliseconds should be between each call.
Note that just because we have specified that the draw function should be called 30 times a seconds, in reality this may not happen. How frequently the draw function is called depends on the speed of the underlying JavaScript engine and the complexity of the code being executed in the draw function. On slow systems the draw function might only be called once per second. The frequency value supplied to the setInterval function can only be considered a best case.