Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 rotate image only not the canvas context

Is there a way to rotate an image inside of a canvas? The only thing that I could find are rotating the whole context of the canvas. I would like to rotate images independently on the canvas.

like image 422
Bryan Williams Avatar asked Dec 05 '25 14:12

Bryan Williams


1 Answers

Unfortunately you can't directly rotate an image.

What you can do if you want to display an image of width W and height H at position X,Y rotate with an angle A (in radian) with a pivot in the middle of your image is :

ctx.translate(-X - W / 2, -Y - H / 2);
ctx.rotate(A);
ctx.drawImage(YOUR_IMAGE, 0, 0);
ctx.rotate(-A);
ctx.translate(X + W / 2, Y + H / 2);
like image 180
Pierre Avatar answered Dec 08 '25 06:12

Pierre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!