Sometimes, we want to resize an image with JavaScript canvas.
In this article, we’ll look at how to resize an image with JavaScript canvas.
How to resize an image with JavaScript canvas?
To resize an image with JavaScript canvas, we use the createImageBitmap
function.
For instance, we write
const imageBitmap = await createImageBitmap(document.getElementById("image"), {
resizeWidth: 300,
resizeHeight: 234,
resizeQuality: "high",
});
document.getElementById("canvas").getContext("2d").drawImage(imageBitmap, 0, 0);
to call createImageBitmap
with the image element and an object with the resize options.
Then we get the canvas with getElementById
.
Next we get the canvas’ context with getContext
.
Finally, we call drawImage
to draw the imageBitmap
onto the canvas.
Conclusion
To resize an image with JavaScript canvas, we use the createImageBitmap
function.