Sometimes, we want to add image to canvas with JavaScript.
In this article, we’ll look at how to add image to canvas with JavaScript.
How to add image to canvas with JavaScript?
To add image to canvas with JavaScript, we call the canvas context drawImage method.
For instance, we write
const canvas = document.getElementById("viewport");
const context = canvas.getContext("2d");
const baseImage = new Image();
baseImage.src = "img/base.png";
baseImage.onload = () => {
context.drawImage(baseImage, 0, 0);
};
to select the canvas with getElementById.
And then we get its context with getContext.
Next, we create an Image object and load it by setting its src property to the image URL.
And then we set baseImage.onload to a function that runs when the image is loaded.
In it, we call context.drawImage with baseImage, 0, and 0 to draw the image into the canvas with the image placed at the upper left corner of the canvas.
Conclusion
To add image to canvas with JavaScript, we call the canvas context drawImage method.