Canvas rotation

2013-02-21

To paint an image rotated properly, first translate the canvas to the center of where the image will be painted. Then apply the rotation. Then either translate the inverse of what you just translated (just same values, negative), or paint the image at -w/2, -h/2 without reversing translation. In code:

Code:
var canvas = getCanvas();
var ctx = canvas.getContext('2d');
var image = getImage();

// where you want to paint image (original x/y of top-left corner, before rotation)
var x = 50;
var y = 120;
var w = image.width;
var h = image.height;

// rotate image 1/10th of a circle
var r = 0.1 * (Math.PI*2);

// coordinate of where center of image should be when painted
var tx = x+w/2;
var ty = y+h/2;

ctx.save(); // always do this unless you know why you dont want to
ctx.translate(tx, ty);
ctx.rotate(r);

// two ways to paint now:
if (true) {
// straightforward method
ctx.translate(-tx, -ty);
ctx.drawImage(x,y,w,h);
} else {
// useful if you want to paint multiple things on the same center. or whatever.
// it also saves a translate call, not sure how much that matters though
ctx.drawImage(-w/2, -h/2, w, h);
}
// undo rotate, this is why we called .save() before
ctx.restore();

The main point to take from this is that you first have to translate the canvas to the anchor point you want to rotate around, before actually rotating. Then you need to either translate back, or simply remember the new canvas origin in your computations.

Hope it helps you