I've been doing some research into representing live statistics visually in web pages. Live meant that bespoke images weren't an option, and I was reluctant (and not well versed enough in the technology) to use flash. This was a perfect opportunity to look in to canvas. Armed with a signed and printed HTML5 Canvas Cheat Sheet (thanks Dom), Jack and I got busy.
If you're impatient, then skip over to the demo: HTML5 Canvas Chart Demo.
Firstly, we did a bit of normalising of our data. For the pie chart we needed to give each piece of data a proportional slice of the circle, and for the blobs it seemed sensible to give them values to add up to 100%. To draw the pie chart, we used the
arc() method with a large stroke size. We also varied the stroke size based on the magnitude of the data which gives a nice dynamic effect. For the blobs, we used the Polar Co-ordinate System to divide the circle up in to equal angles based on how many data points there are, and plot the blobs with a radius based on the size of the data.
Here's a screenshot of the result:
So that's all pretty and stuff, but it lacks bells and whistles. We decided to introduce some animation and easing. The process goes something like this:
- We want the pie to start off with equally sized sections that animate to represent the data we've got.
- We've got a draw-once type function
drawPie(). Let's factor out the all of the drawing to another method called
drawShapeIncrementFromEqual()which takes an argument called
drawPie()method should now repeatedly call the
progressargument between 0 and 1.
drawShapeIncrementFromEqual()should draw the chart at its start position if
progress = 0, and at it's finishing position if
progress = 1, and a linear progression for all values between.
- Now in our
drawPie(), instead of passing our
progressvariable straight to the drawing method, we can run it through a custom easing method. Here we've chosen a nice bouncing ease.
Creating the Fallback
With a bit of CSS and some help from jQuery we can make the fallback data look nice, and even animate in some bar charts. The check for canvas support is simple:
getElementById("myCanvasId").getContext will be undefined if canvas is not supported. Take a look at the fallback in your normal canvas capable browser; I've broken the canvas tag to make the fallback kick in.
The thing that these charts are missing most is a key. What use is the data if we don't know what it represents? Obviously if we were to use this in a real-life situation then we would make one, but we confess we spent longer on tweaking the easing method than worrying about this!
Like what you've read?