Rotating around an arbitrary point: HTML5 Canvas

To rotate around a point you need to do 3 steps.

  • First translate the context to the center you wish to rotate around.
  • Then do the actual rotation.
  • Then translate the context back.

Like this:

var canvas = document.getElementById("testCanvas");
var dc     = canvas.getContext("2d");
var angle = 0;
window.setInterval(function(){
    angle = (angle + 1) % 360;
    dc.clearRect(0, 0, canvas.width, canvas.height);

    dc.save();
    dc.fillStyle = "#FF0000";

    dc.translate(150,200); // First translate the context to the center you wish to rotate around.
    dc.rotate( angle*Math.PI/180 ); // Then do the actual rotation.
    dc.translate(-150,-200); // Then translate the context back.

    dc.beginPath();
    dc.moveTo(100, 100);
    dc.lineTo(200, 100);
    dc.lineTo(200,300);
    dc.lineTo(100,300);
    dc.closePath();
    dc.fill();

    dc.restore();
}, 5);

When you rotate the canvas, it rotates from the origin (0, 0), so your rectangle ends up getting rotated off the screen.

See this example where it's only rotated 45 deg: http://jsfiddle.net/wjLSm/

One way to fix this is to translate the canvas by its width & height/2: http://jsfiddle.net/wjLSm/1/ (then 0,0 is at the middle -- be aware of this)