Categories
JavaScript Answers

How to add image to canvas with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *