Games — Html5 Canvas

To create an animation by using an HTML5 canvas you need to display a sequence of 2D elements by using the API provided by the canvas object. This is typically something you achieve through iteration, where in each repeated cycle you replace the element drawn previously with a new element. One way to achieve this is to create a game loop.

In Javascript you can use the setInterval method to set up this game loop.

Note: the second parameter of the setInterval method enables you to specify a desired amount of milliseconds between each iteration. Here I've specified 1000 / 60 milliseconds, which is a value of about 16. By doing this I've expressed my desire that the loop method be called roughly 60 times per second, providing an animation running at approximately 60 frames per second (fps).

There’s no guarantee that a desired fps will be honoured by the browser. If you create complex animations, run them on a low-spec device, or have to compete for CPU time, your fps will drop. To animate at constant speed, 200 pixels per second for example, you need to calculate the time delta since the last frame, and then move the element proportionally.

For example, knowing where an element is, where it needs to be after a known period of time has elapsed, and then how much of time has passed, you can calculate where the element should be next. This is commonly referred to as alerp, which is an abbreviation for linear interpolation. Linear interpolation is a function used to derive an unknown value that falls between two known values i.e. 20% between black (R:0, G:0, B:0) and white (R:255, G:255, B:255) is a shade of grey (R:51, G:51, B:51).

Each time this game loop executes the elapsedSeconds variable is calculated from the time delta between each execution. In this example there will be a delta of approximately 16 milliseconds, which when divided by 1000 gives us 0.016 seconds or 1.6% of a second. Therefore if you wanted to animate something at 200 pixels per second you simply move it 200 * elapsedSeconds, which is approximately 3.2 pixels.

You can use the same method to synchronise an event to a point within an animation i.e. change the colour of the element after 5 seconds by calculating the delta time between now and the start of the game loop’s execution.

As the need for this type of game loop becomes more prevalent, browser vendors are designing new ways to solve the situation. For instance, the newly designed requestAnimationFrame API (available in tip browsers) tells the browser to execute a specified game logic/animation method before drawing the next frame. The browser itself is responsible for choosing the best moment to execute the code and so can benefit from not processing while minimized etc.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store