Bookmark with delicious tweet this site

RGraph: Javascript charts and graph library - Animating your charts

[No canvas support]

Animating your charts 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 revert the canvas back to transparency. 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 chart.

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 charts 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 chart 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. Animated segment separation is now (April 2011) available as an alternative tooltip highlight mode:

myObj.Set('chart.highlight.style', 'explode');