An example of the rotate function

  Read comments... Posted on 10th February 2012

An example of the rotate function. It rotates the coordinate system of the canvas so a straight line that you draw is actually drawn at an angle.

This page shows how to use the RGraph.rotateCanvas() method to create a spinning effect.

[No canvas support]


This is an example of the canvas rotate function being used to rotate the canvas before the chart is drawn The angle is controlled by the range input (best viewed in Chrome, Safari or Opera) below the canvas - and the canvas is being continually refreshed. Hence the spinning effect.

Rotating the canvas

The default rotate() function simply rotates the canvas around the [0,0] coordinates. The angle is measured in RADIANS - not degrees - which is important to remember or you can get some unexpected results. To convert from degrees to radians you can use the RGraph function:


Or you could use these functions instead:

    Number.prototype.toRadians = function ()
        return this * (Math.PI / 180);
    Number.prototype.toDegrees = function ()
        return this * (180 / Math.PI);

It's important to remember that the rotation is always centered about the [0,0] coordinates. This is where the RGraph.rotateCanvas() differs as you can pass in the coordinates that you want the canvas to be rotated about. This results in the RotateCanvas function translating to those coordinates, rotating the canvas and then translating back. like this:

RGraph.rotateCanvas(canvas, x, y, radians);

So this means that if you wanted to rotate the canvas about its center you do this:

var x = canvas.width / 2;
var y = canvas.height / 2;

RGraph.rotateCanvas(canvas, x, y, radians);

In the example above the canvas is continuously rotated every 50ms and the angle is increased or decreased by the range input.

Example code

The code to achieve the spinning effect is this:

    onchange="gAngle = Number(this.value);"
    style="width: 250px"

    gAngle  = 0;
    gCanvas = document.getElementById("cvs");
    function DrawChart ()
        // Instead of using the Clear method, this clears the canvas and resets the rotation
        gCanvas.width = gCanvas.width;

        // This resets the antialiasing fix - so when the chart is drawn again the canvas can be "fixed" again
        gCanvas.__rgraph_aa_translated__ = false;

        RGraph.rotateCanvas(gCanvas, 175, 175, RGraph.degrees2Radians(gAngle));

        var rose = new RGraph.Rose({
            id: 'cvs',
            data: [4,3,8,6,5,9,6,4],
            options: {
                colorsSequential: true,
                colorsAlpha: 0.5,
                margin: 5,
                labelsAxes: 'n',
                textAccessible: false
        setTimeout(DrawChart, 50);
If you like RGraph please share it: