How to Resize Then Crop an Image in the HTML5 Canvas with JavaScript?

Sometimes, we want to resize then crop an image in the HTML5 canvas with JavaScript.

In this article, we’ll look at how to resize then crop an image in the HTML5 canvas with JavaScript.

Resize Then Crop an Image in the HTML5 Canvas with JavaScript

To resize then crop an image in the HTML5 canvas with JavaScript, we can call drawImage with several arguments.

For instance, we can write:

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

to add a canvas element.

Then, we write:

const image = new Image()
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d');
image.src = 'https://picsum.photos/500';
image.onload = () => {
  ctx.drawImage(
    image,
    20, 20,
    50, 50,
    20, 20,
    100, 100
  );
}

We create an image with the Image constructor.

Then we select the canvas element with document.querySelector.

And then we call getContext to get the context.

Next, we set the src property of the image to the image’s URL.

Then we set the onload property to a function that calls drawImage with the image to draw it.

The 2rd and 3th arguments of drawImage are the x and y coordinates of the top left corner of the source image to clip.

The 4th and 5th arguments of drawImage is the width and height of the area of the source image to clip.

The 6th and 7th arguments of drawImage is the x and y coordinates of the source image on the canvas.

And the last 2 arguments are the width and height of the destination image on the canvas.

Now we should see the cropped and resized image displayed on the canvas.

Conclusion

To resize then crop an image in the HTML5 canvas with JavaScript, we can call drawImage with several arguments.