HTML5Feature

Four essential HTML5 canvas tips

Creative programmer Hakim El Hattab provides four top tips to help you make the most out of the canvas element. He also explains how the little monster that inspired our current 404 page was made possible

Performance

When working with animation on canvas, performance can be a challenge since bitmap operations are very processing-expensive, especially at high resolutions. One important  optimisation rule to follow is to re-use as many pixels as possible between frames. What I  mean by that is the fewer pixels that need to be processed with each frame, the faster your program will run.

A good example of this is that when erasing pixels with the clearRect(x,y,w,h) method, it’s very beneficial to clear and redraw only the pixels that have changed and not, for instance, a full  screen 1920x1280 sized canvas. Unlike the Flash Player’s redraw regions this management of “dirty regions” needs to be done manually for canvas.

Compositing

A very powerful tool at hand when working with canvas is the composite modes (<2DContext>.globalCompositeOperation), which can be used to apply masks and control layering amongst other things. There’s a wide array of available composite modes and when combined they can perform some very powerful tasks.

This critter was made possible by the compositing capabilities of canvas. For example, the teeth are larger than what you can see within the mouth to allow for it to open and close
Antialiasing

To allow for sub-pixel drawings, all browser implementations of canvas employ antialiasing (although this is not a requirement in the HTML5 spec). Antialiasing can be important to keep in mind if you want to draw crisp lines and notice the result looks blurred. To work around this you will need to either round up to integer values or offset by half a pixel depending on whether you’re drawing fills or strokes.

Clearing the canvas

To clear the entire canvas of any existing pixels you would normally use the clearRect(x,y,w,h) function but there is another option available. Whenever the width/height of the canvas are set, even if they are set to the same value repeatedly, the canvas is reset. This is good to know when working with a dynamically sized canvas as you’ll notice your drawings disappear every time it is resized.

Inspired by the little critter above, Bakemono, Hakim created our latest 404 page. The animation is entirely code generated and drawn on an HTML5 canvas element. If you're interested in how this was created, have a look at the source code on GitHub.

Subscription offer

Log in to Creative Bloq with your preferred social network to comment

OR

Log in with your Creative Bloq account

site stat collection