Categories
JavaScript Answers

How to Draw and Image on the HTML5 Canvas at an Angle with JavaScript?

Spread the love

To draw and image on the HTML5 canvas at an angle with JavaScript, we can call the rotate and translate methods on the canvas context.

For instance, we write:

<canvas style='width: 300px; height: 300px'></canvas>

to add the canvas.

Then we write:

const image = new Image()
image.src = 'https://picsum.photos/200'
image.onload = () => {
  const canvas = document.querySelector("canvas");
  const context = canvas.getContext("2d");
  const x = canvas.width / 2;
  const y = canvas.height / 2;
  const width = image.width;
  const height = image.height;
  const angleInRadians = Math.PI / 4
  context.translate(x, y);
  context.rotate(angleInRadians);
  context.drawImage(image, -width / 2, -height / 2, width, height);
  context.rotate(-angleInRadians);
  context.translate(-x, -y);
}

to create an image with the Image constructor.

Then we set the src of the image to the URL of the image we want to load.

Then we set the onload property to a function that draws the image onto the canvas.

In the function, we get the canvas with document.querySelector.

Then we call getContext to get the context.

Next, we set the x and y coordinates of the top left corner of the image.

Then we set the width and height of the image.

Next, we set the anglesInRadians to rotate the image by.

Then we call translate to translate the image horizontally and vertically by x and y respectively.

Then we call rotate to rotate the image by angleInRadians.

Next, we call drawImage to draw the image with the x and y coordinates of the top left corner and the width and height respectively as the arguments.

Then we call rotate and translate to do the rotation and translation again.

Now we should see a rotated image on the canvas.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *