Sometimes, we want to add an image to the canvas with JavaScript.
In this article, we’ll look at how to add an image to the canvas with JavaScript.
How to add an image to the canvas with JavaScript?
To add an image to the canvas with JavaScript, we use the 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 get the canvas with getElementById
.
Then we get the canvas context with getContext
.
Next, we create a new img element with the Image
constructor.
Then we set its src
attribute by setting the src
property.
We then set the onload
property to a function that’s called when the image is loaded.
In it, we call drawImage
to draw the baseImage
.
Conclusion
To add an image to the canvas with JavaScript, we use the drawImage
method.