Fiddling with the HTML5 Canvas

I’ve been doing some experimenting with HTML5’s Canvas element. After some brushing up on Javascript, I started working on a couple of proof-of-concept scripts to see how well the platform can be used.

I have not been disappointed. Javascript, as a language, has evolved quite a bit since the old days of document.write(), with DOM editing as the one true way to manage dynamic content. Having said that, I find that Javascript is still quirky and flawed.

Here’s a short script I wrote (fewer than 160 lines) that animates a girl wearing the traditional Oktoberfest outfit. She walks back and forth within a given 500×500 area. This is not a video, your browser is doing the math to update her animations and move her around in realtime!

You should be able to see the demo just above this message, if you have a fairly recent browser that supports the HTML5 Canvas element. I was actually surprised about how mainstream Canvas support is: Chrome ≥ 22, Firefox ≥ 15, IE ≥ 9; Opera ≥ 12.1; Safari ≥ 5.1, Android ≥ 2.1 and Safari Mobile ≥ 3.2, all support this new element.

The animation atlas was taken from this cool website with resources free to use. The script “slices” the image, taking the appropriate frames to draw depending on the time simulation and the direction the character is walking towards (left or right).

Sprite animation atlas.
Sprite animation atlas.

Despite Javascript’s gotchas, with the addition of the HTML5 Canvas element, it’s become a nice tool that allows hacking together some easy 2D (or even 3D!) graphics and display them in a browser.

See you next time!