Working with HTML5 Canvas

Since I changed jobs a little over a month ago, I've found myself in a position of needing to brush up on a few skills, and also get a chance to learn some new ones.  Most recently, I've had the opportunity to delve into the HTML5 canvas tag.  For those who don't know, canvas is the HTML5 way of drawing things on screen using Javascript, and an alternative to SVG.

My use for it was to build a very bespoke graph which needed some lines running across it (but not a grid), information from a data source between those lines, and within the bars on the graph, and also for it to be adjusted by user input.  Fun times.

Initially I hadn't heard of canvas, because I hadn't done that much work with HTML5, and certainly never used it, so it was a little daunting at first.  I had initially started the graph using clever placement of div's, and had the whole thing working nicely after about half a day.  After canvas was brought to my attention, I re-wrote it in a little over an hour.  The moral of that story is "there is sometimes a better way", and also "new topics aren't always hard, so never be afraid to learn".

There's a lot more to canvas than I used, and more than I will go into here, but simply put to start using it, you create markup like the following:

<canvas width="300" height="225"></canvas>

That will, as you can probably guess, create a canvas 300px wide and 225px high.  There's an oddity here that whilst most elements are encouraged to have things like dimensions in CSS and have a class or ID allocated to them, canvas works much better if the dimensions are set in the tag.  It is, after all, an image; and we are encouraged to add dimensions to images in markup.  I found that when the dimensions were set in CSS and applied by a class or ID, the resultant image was blurry and generally of poor quality.  Set the dimensions in the tag and everything is nice and crisp.

I've also found it much easier if you style everything you possibly can using canvas.  Any colours, borders or anything else you might need, do it all within the canvas container itself.  The results are much better.

Finally, when building your canvas, the JavaScript is going to get fairly large for anything other than very basic things.  There will be a lot of things you will re-use and re-set throughout the canvas (probably) so remember, variables are your friend.  If you think it might be re-used, make a variable for it.  If you don't, you'll be spending a lot of time checking through the different parts of your code to change something as simple as a colour on a part of the image because you've decided you want it red instead of blue, and you've reset the colour in 40 different places.