How to rotate an image in canvas?

by arnoldo.moen , in category: Javascript , 4 months ago

How to rotate an image in canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 4 months ago

@arnoldo.moen 

To rotate an image in a canvas using JavaScript, you can follow these steps:

  1. Get a reference to the canvas element and the 2D drawing context:
1
2
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');


  1. Create an Image object and load the image:
1
2
3
4
5
6
var img = new Image();
img.onload = function() {
    // Draw the image on the canvas
    ctx.drawImage(img, 0, 0);
};
img.src = 'image.jpg'; // Replace 'image.jpg' with the URL of your image


  1. Use the rotate method of the canvas context to rotate the image:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var angleInDegrees = 45;
var rotationPointX = canvas.width / 2; // Rotate around the center of the canvas
var rotationPointY = canvas.height / 2;

ctx.translate(rotationPointX, rotationPointY);
ctx.rotate(angleInDegrees * Math.PI / 180); // Convert degrees to radians
ctx.translate(-rotationPointX, -rotationPointY);

// Redraw the image after rotation
ctx.drawImage(img, 0, 0);


  1. Make sure to clear the canvas before rotating the image if you want to remove the previous image:
1
ctx.clearRect(0, 0, canvas.width, canvas.height);


  1. You can then use this code inside a function that is called when an event occurs or in an animation loop to continuously rotate the image.


Note: Keep in mind that rotating an image multiple times or rotating and then translating the image multiple times can lead to degradation in the image quality. To maintain the image quality, you may need to redraw the image from its original source each time it is manipulated.