Sometimes, we want to resize then crop an image with HTML canvas and JavaScript.
In this article, we’ll look at how to resize then crop an image with HTML canvas and JavaScript.
Resize Then Crop an Image with HTML Canvas and JavaScript
To resize then crop an image with HTML canvas and JavaScript, we can call the drawImage
method with the original image with the coordinates of the boundaries of the image we want to crop.
For instance, if we have the following HTML:
Image: <br/>
<img src="https://i.stack.imgur.com/I4jXc.png" /><br/>
Canvas: <br/>
<canvas id="canvas" width="300" height="300"></canvas>
we write:
const image = new Image()
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d');
image.src = 'https://i.stack.imgur.com/I4jXc.png';
image.onload = () => {
ctx.drawImage(image,
70, 20,
50, 50,
0, 0,
100, 100);
}
to do the cropping.
We create an image element with the Image
constructor.
Then we get the canvas with document.getElementById
.
Next, we get the canvas context with getContext
.
Then we setr the src
property of thr image to the image URL.
This will trigger the image.onload
method to run.
In the onload
method, we call drawImage
with the
image
- x and y coordinates of the top left corner
- width of the part of the source image to get relative to the top left corner
- height of part of source image to get relative to the top left corner
- x and y coordinates of the top left corner of the cropped image
- width and height of the cropped image
in this order.
Therefore, we should get the ‘o’ from the word ‘Google’ in the image.
Conclusion
To resize then crop an image with HTML canvas and JavaScript, we can call the drawImage
method with the original image with the coordinates of the boundaries of the image we want to crop.