0

I need multiple images placed into canvas. The images should be rotated, resized and placed at particular coordinates. So in general I need

ctx.drawImage(img,left,top, width, height); 

but rotated.

I have come up with this function:

function drawRotated(image, context, angle, left, top, width, height) {
    context.save();
    context.translate(width / 2, height / 2);
    context.rotate(Math.PI / 180 * angle);
    context.drawImage(image, left - width / 2, top - height / 2, width, height);
    context.restore();
}

But it doesn't seem to be working exactly as needed. It looks like after rotation I need to recalculate the position with the new width and height that rotation has turned the image into. But I can't figure out the math. Do I need to actually do trigonometry stuff to calculate all that, or is there a simple solution? Thanks.

Timur Gafforov
  • 771
  • 3
  • 10
  • 28

1 Answers1

0

I think you just need to replace the translation step with

context.translate(left + width / 2, top + height / 2);

the same rotation, and then

context.drawImage(image, - width / 2, - height / 2, width, height);

thus

function drawRotated(image, context, angle, left, top, width, height) {
    context.save();
    context.translate(left + width / 2, top + height / 2);
    context.rotate(Math.PI / 180 * angle);
    context.drawImage(image, - width / 2, - height / 2, width, height);
    context.restore();
}
Paul Janssens
  • 622
  • 3
  • 9
  • Wow, that actually did work. There are so many solutions with like 50-200 lines of code. But this one actually works. Thanks, it's awesome. Could you edit the answer with full function so that I could mark it as the answer? – Timur Gafforov Jul 31 '20 at 05:43