Search code examples
javascriptrotationhtml5-canvas

How to rotate an image on an HTML5 canvas around center


This is practically an exact duplicate of 20 other questions, but I can't find the correct answer anywhere. All I need is a way to rotate an image around its center. I have tried this (using strokeRect as a placeholder):

ctx.translate(x, y);
ctx.rotate(-angle);
ctx.strokeRect(x, y, 150, 100);
ctx.rotate(angle);
ctx.translate(-x, -y);

I have tried dozens of variations on this and looked at every Stack Overflow post on the topic, with no function that draws an image rotated on its center by a certain amount. That's all I want.


Solution

  • You need to translate by the desired center plus half the size of the image, rotate, then translate back by half the size of the image. Otherwise your are rotating around the corner. I used save and restore instead of rotating and translating back after the draw, because it's faster.

    ctx.save();
    ctx.translate(x + width/2, y + height/2);
    ctx.rotate(-angle);
    ctx.translate(-width/2, -height/2);
    ctx.strokeRect(0, 0, 150, 100);
    ctx.restore();