Rescaleable HTML5 Canvas

One of the major disadvantages of Flash is its lack of resizability. It would be nice if, when developers start switching over to the HTML5 Canvas, they at the same time start paying attention to scaleability.

Unfortunately all the Canvas tutorials I have seen so far are stuck firmly in the bad old days of fixed pixel sizes. I have even encountered one site that said point-blank that if you want resizeability you will have to use SVG. Rubbish!

Resizeability is certainly achievable, although you do need to make some effort. I've made a small demo here. So far I have spent very little time on Canvas, so the demo is very unambitious, but hopefully makes the point. The canvas resizes to fit whatever window it finds itself in (within given minimum and maximum sizes, which are themselves easily adjustable). Try resizing the window.

The Canvas element is unfortunately not available in this browser, so this page does not show anything meaningful. Browsers supporting the Canvas element include Opera 10+, Firefox 3.0+ and Chrome 3+.

There are two scripts, one containing the scaling routines themselves and the other contains the demo, which makes use of the scaling routines. I'm not going to describe the code in detail – it's pretty straightforward for anyone who knows enough Javascript to consider doing things with Canvas – but here are a few of the main features.

  1. An HTML5 canvas cannot be sized using CSS; it has to be done with HTML pixel attributes or script. I leave the HTML element unsized but use script to give it the same width as some other element of the page (this example uses the header element). This other element can be sized using any CSS you like.
  2. When drawing the canvas, the x co-ordinates are specified as a percentage of the x-axis length. The y co-ordinates can be specified as a percentage of the y-axis (if you want something e.g. half-way down) or as a percentage of the x-axis (useful for things like drawing squares).
  3. Normally co-ordinates are scaled to whole-pixel positions. However a curiosity of Canvas is that if you want to draw one-pixel wide lines (or any other odd number of pixels) you have to specify pixel positions in the middle of a pixel. The "midpx" routines do this.
  4. Font sizes in the canvas are in pixels rather than ems; however this does not matter since they are resized anyway.

Other features: the page includes a check for Canvas support in the Canvas element (try it in IE 7 or 8). Within that check is a check for disabled Javascript.

If desired a maximum and minimum canvas size can be defined; this is done in the CSS which defines the element which the Canvas follows - in this case the header element.