Matthew Cox Team : Web Development Tags : Technology Web Development

Take an existing product and put a clock in it

Matthew Cox Team : Web Development Tags : Technology Web Development

 

In the immortal words of Homer Simpson “People are afraid of new things. You should have taken an existing product and put a clock in it or something.” So this is my new blog post, with a clock in it.

Cast your mind back to late 2010, IE 9 was just over the horizon and with it was coming support for the canvas tag. Now before anyone gets their pitchforks to complain and I have to bring out the old vat of boiling oil to respond, yes, I’m aware that every other browser already supported the canvas tag, but unfortunately we build websites for consumers, not just other web developers. As such we need something to be well supported before we start putting it into production, so at the rate IE users upgrade we should be just about good to start using the canvas tag today.

Anyway, in an attempt to figure out what all the fuss was about I decided to sit down for an afternoon and write a thing that would use the canvas tag in some fashion to do animation of some variety. So now 4 years later I figured it was about time to finally write the blog that should have accompanied this experiment years ago.

For those that aren’t aware, the canvas tag is a magic tag that allows access to a 2d drawing API from JavaScript. It’s essentially the W3C finally agreeing that not all content on the internet is semantic and giving web developers a sandbox where they can play like its 1995 and they are coding GDI+ for the Win32 API (or any one of dozens of other similar 2D drawing APIs). As such if you have used any drawing API in the past it should look fairly familiar to you.

As for the clock, my goal was only to get a feel for the API hence the simple example, but there were a few key areas I wanted to over engineer:

  • Back buffering – clearing then writing everything direct to the screen results in flicker so for the canvas tag to be useful I wanted to find a way to implement a back buffer.
  • Layering – I didn’t want to redraw the entire clock each time. While it probably would have been fast enough for the simple clock, it wouldn’t have been suitable for any more complex scenes. As such the clock face is stored in a separate layer and only the clock hands are drawn each animation tick.

The solution to the issue of back buffering was simply to create a canvas tag but not add it to the page DOM, which I was a little surprised worked. I know there are often all kinds of issues writing to non-visible targets on a page since by the nature of it being hidden, it doesn’t have a location. As for the layering, it’s a simple matter of calling getImageData to get the content of the back buffer to store for later use.

If you would like to take a look at the script you can get it here.