HTML 5 Canvas in Blogger
The purpose of the previous post with the port of Starlings to JavaScript was to learn how viable it would be to use the HTML 5 canvas element to embed graphics in our blog. The purpose of this post is to record what we learned.
There are two basic categories of issues. The first is support for the canvas element. The second has to do with the fact that it’s hard to put things in the head element of a blog post.
Canvas Support
The most obvious problem is the fact that Internet Explorer doesn’t support the canvas element yet. At some point I’ll try out ExplorerCanvas, but I didn’t want to add that to the mix on this first example.
In Chrome, the canvas element seems to work great on every platform we’ve tried.
It works OK in Safari on the Mac, but it’s a bit slower than Chrome.
It draws OK in Firefox on the Mac, although it is quite a bit slower. Firefox also has the problems with mouse event coordinates which I describe below. The other tricky bit with Firefox is getting the coordinate system correct on mouse events. In a browser which supports the clientX and clientY fields in the mouse event, then you’re all set. Otherwise it gets a bit tricky. I tried using the layerX and layerY fields in that case, but that’s not the entire solution. There appears to be a Y offset which still needs to be accounted for.
It sort of works in Safari on the iPhone. It’s really, really, really slow. The mouse event handling appears to be OK in this case, but it’s so slow that it is really hard to tell. It also has problems loading and blting the image sometimes.
We haven’t tried it on various other combinations of browsers and platforms. If you have a different setup, you could leave us a comment telling us how it works for you.
Scripting in the Body of the Post
The other problem is that it’s difficult to insert scripts into the head element of a blog post. This means that all of the scripting has to be done in the body element. It turns out that this adds a bit of difficulty. Each script element is executed as it is encountered when the page is first loaded. This causes problems with asynchronous operations like image loading.
If you look at the source for that page, you’ll see that I added the background image for the canvas as a separate img element with an onload function which started the interval timer which draws the canvas. This approach seems to work reasonably well, but you can see a tiny rectangle to the right of the canvas where the img element is.