To add image to canvas with JavaScript, we call 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 select the canvas with getElementById
.
And we get its context with getContext
.
Next we create an img element with the Image
constructor.
And then we call drawImage
with baseImage
when the image is loaded.
We load the image by setting the src
property to the image URL string.