How to rotate the canvas image?

by dalton_moen , in category: Javascript , a month ago

How to rotate the canvas image?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , a month ago

@dalton_moen 

To rotate the canvas image, you can use the following steps:

  1. Load the image onto the canvas using an image object or file input.
  2. Use the rotate() method of the canvas context to rotate the image by a specified angle in radians.
  3. Call the drawImage() method to draw the rotated image onto the canvas.
  4. You can also translate the canvas to reposition the rotated image if needed.


Here's an example of rotating an image on the canvas by 90 degrees clockwise:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// Load image onto canvas
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var image = new Image();
image.src = 'path/to/image.jpg';
image.onload = function() {
    // Rotate image by 90 degrees
    ctx.save();
    ctx.translate(canvas.width / 2, canvas.height / 2);
    ctx.rotate(90 * Math.PI/180);
    ctx.drawImage(image, -image.width / 2, -image.height / 2);
    ctx.restore();
};


This code snippet first loads an image onto the canvas and then rotates it by 90 degrees using the rotate() method. It also centers the rotated image on the canvas. You can customize the angle of rotation and positioning of the image according to your requirements.