How To Resize Image With JavaScript Canvas? - The Web Dev

Sometimes, we want to resize image with JavaScript canvas.

In this article, we’ll look at how to resize image with JavaScript canvas.

How to resize image with JavaScript canvas?

To resize image with JavaScript canvas, we call drawImage with the given image width and height.

For instance, we write

const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const img = new Image(); img.onload = () => { canvas.height = canvas.width * (img.height / img.width); const oc = document.createElement("canvas"); const octx = oc.getContext("2d"); oc.width = img.width * 0.5; oc.height = img.height * 0.5; octx.drawImage(img, 0, 0, oc.width, oc.height); octx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5); ctx.drawImage( oc, 0, 0, oc.width * 0.5, oc.height * 0.5, 0, 0, canvas.width, canvas.height ); }; img.src = "https://picsum.photos/200/300";

to set the img.onload property to a function that runs when the image is loaded.

In it, we set the canvas height and width with

canvas.height = canvas.width * (img.height / img.width);

We resize the the image to 50% of its original size with

const oc = document.createElement("canvas"); const octx = oc.getContext("2d"); oc.width = img.width * 0.5; oc.height = img.height * 0.5; octx.drawImage(img, 0, 0, oc.width, oc.height);

Then we resize it to its final size with

ctx.drawImage( oc, 0, 0, oc.width * 0.5, oc.height * 0.5, 0, 0, canvas.width, canvas.height );

We draw the resized image by drawing the image in the oc canvas width 50% of the size of the oc canvas.

Conclusion

To resize image with JavaScript canvas, we call drawImage with the given image width and height.

Từ khóa » Html Canvas Stretch Image