Share: Bookmark with delicious tweet this site Post to Facebook

RGraph: HTML5 canvas graph library - Animating your graphs

[No canvas support]

Animating your graphs is a relatively easy affair, whilst not being supported natively as it would only serve to over-complicate the RGraph libraries. The way to do it is to use the function RGraph.Clear(canvas), passing it your canvas object that is returned by document.getElementById(). By default this will cover the canvas in white. You can change this by passing it the color you want it to use as the second (optional) argument. You could even use a gradient if you wanted. Then you can simply redraw the entire graph.

One thing you should note, is that you may have to specify the scale manually, to prevent it from changing from frame to frame. This can be done by using the chart.ymax property.

You can review the source of this page if you need further help. Two global variables are set - the number of frames and the current frame number (which starts at one). The graphs are then drawn with appropriate data (ie the data multiplied by the frame number over the total number of frames). If the frame number is less than the total number of frames, the frame number is incremented and the function (window.onload) is called again after a small delay.

Animation using jQuery

[No canvas support]

You can if you prefer use an external library for animation, like jQuery.

The graph to the right is animated using jQuery. In the example the width is maintained by placing the canvas within a DIV which has the width/height CSS attributes set.

In this instance, the Google hosted jQuery is used.


CSS animation versus <canvas> animation

As you can see from the above examples, or if you build your own animations, CSS animation (which jQuery does) can be much smoother. This is because CSS animation (ie changing the CSS attributes) does not have the side effect of clearing the canvas, and so does not incur a redraw.

An Animated Pie chart

This example is of the Pie chart, with animated segment separation. Segment separation itself is part of the Pie chart, but it's not animated. It's on a sparate page to make it easier for you to dissect the page if you want to.