Animation Loop

To make anything move on the Canvas, you need an animation loop. An animation loop is a function called over and over on an interval. The function is used to clear the Canvas and redraw it with updated images, text, video, and drawing objects.

The easiest way to create an interval for animation is to use a simple setTimeout() loop. To do this, we create a function named gameLoop() (it can be called anything you like) that uses window.setTimeout() to call itself after a specified time period. For our application, that time period will be 20 milliseconds. The function then resets itself to call again in 20 milliseconds and then calls drawScreen().

Using this method, drawScreen() is called every 20 milliseconds. We will place all of our drawing code in drawScreen(). This method does the same thing as using setInterval() but, because it clears itself and does not run forever, is much better for performance:

function gameLoop() {
    window.setTimeout(gameLoop, 20);
    drawScreen()
}

gameLoop();

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.