File Under: HTML5, JavaScript, Programming

Tips and Tricks for Better HTML5 Canvas Animations

HTML5If the latest flashy HTML5 experiments have you fired up to experiment with HTML5′s canvas element yourself, one seasoned developer has some advice for newcomers — particularly those coming from Flash backgrounds.

Hakim El Hattab, whose experiments with HTML5 were featured in our round up here on Webmonkey earlier this week, has a short, instructional write up on the Canvas tag that includes some tricks to make your JavaScript experiments run smoother and faster.

Perhaps the most useful tidbit in the article is that “bitmap operations are very processing expensive,” and whenever possible you should reduce and reuse as many pixels as you can between frames. While browsers are getting faster, optimization will always be key (the same is true of Flash animations).

Another thing Hakim recommends you keep in mind if you’re coming from a Flash background is that, “unlike the Flash Player’s redraw regions, this management of ‘dirty rectangles’ needs to be done manually for canvas.” Think of it as garbage collection — like C or C++, you’re in charge of cleaning up after your code when it comes to redrawing in Canvas.

Along the same lines is his tip for clearing your canvas: just reset the width and height. This is also good know if you want to avoid clearing your canvas.

The advice is good for those who have some experience drawing with JavaScript in canvas tags, but if you’re totally new to the animation possibilities in HTML5, we’d recommend starting with Mark Pilgrim’s online book Dive into HTML5, which has an entire section devoted to Canvas. Once you’ve mastered the basics, this handy HTML5 Canvas cheat sheet is good to keep on hand for looking up the various methods and attributes available.

See also: