Share: Bookmark with delicious tweet this site Post to Facebook

RGraph: HTML5 canvas graph library - An example of an animated & interactive Pie chart

[No canvas support]

This example shows how you can animate the Pie chart segment seperation, making it possible to introduce some sort of highlighting, which could be used in a presentation of sorts.

It's here on it's own page to make it easier for you to dissect the page if you want to implement this.


<script>
    // Intentionally a global variable
    pie = new RGraph.Pie('cvs', [24,43,51,16,26,23,35]);
    pie.Set('chart.strokestyle', 'rgba(0,0,0,0)');
    pie.Set('chart.labels', ['Richard','John','Kev','Lou','Pete','Fred','Bob']);
    pie.Set('chart.labels.sticks', true);
    pie.Set('chart.radius', 100);
    pie.Draw();
    
    RGraph.Register(pie);
     
    pie.canvas.onclick = function (e)
    {
        
        var segment = pie.getSegment(e);
        if (segment && segment.length && typeof(segment[5]) == 'number') {
    
            RGraph.Redraw();

            var exploded = [];

            exploded[segment[5]] = 0;
            
            // Show a tooltip (using the labels coming from the pie chart)
            //RGraph.Tooltip(pie.canvas, pie.Get('chart.labels')[segment[5]], e.pageX, e.pageY, segment[5])

            setTimeout(function () {pie.Set('chart.exploded', exploded);RGraph.Clear(pie.canvas);pie.Draw(); exploded[segment[5]] += 7;}, 25);
            setTimeout(function () {pie.Set('chart.exploded', exploded);RGraph.Clear(pie.canvas);pie.Draw(); exploded[segment[5]] += 7;}, 50);
            setTimeout(function () {pie.Set('chart.exploded', exploded);RGraph.Clear(pie.canvas);pie.Draw(); exploded[segment[5]] += 7;}, 75);
            setTimeout(function () {pie.Set('chart.exploded', exploded);RGraph.Clear(pie.canvas);pie.Draw(); exploded[segment[5]] += 7;}, 100);
            setTimeout(function () {pie.Set('chart.exploded', exploded);RGraph.Clear(pie.canvas);pie.Draw(); exploded[segment[5]] += 7;}, 125);
        } else {
            pie.Set('chart.exploded', []);
            RGraph.Redraw();
        }
    }


    /**
    * The onmousemove event for changing the pointer only
    */
    pie.canvas.onmousemove = function (e)
    {            
        var segment = pie.getSegment(e);
        
        if (segment && segment.length && typeof(segment[5]) == 'number') {
            pie.canvas.style.cursor = 'pointer';
        } else {
            pie.canvas.style.cursor = 'default';
        }
    }
    
    /**
    * This is here to redraw he Pie, getting rid of any "selected" segment
    */
    window.onclick = function ()
    {
        RGraph.Clear(pie.canvas);

        pie.Set('chart.exploded', []);
        pie.Draw();
    }
</script>

« Back to animation page