Categories
JavaScript Answers

How to Add an Image to a Canvas Element with JavaScript?

Spread the love

Sometimes, we want to add an image to a canvas element with JavaScript.

In this article, we’ll look at how to add an image to a canvas element with JavaScript.

Add an Image to a Canvas Element with JavaScript

We can add an image to the canvas with the drawImage method.

For instance, if we have the following canvas:

<canvas style='width: 300px; height: 300px'></canvas>

Then we can write the following JavaScript to draw an image in it:

const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');
const baseImage = new Image();
baseImage.src = 'https://i.picsum.photos/id/441/200/300.jpg?hmac=QKMN_HV9XLlzyUWdanPyq2Qz8FJmYYH5Q0CjPACcnsI';
baseImage.onload = () => {
  context.drawImage(baseImage, 0, 0);
}

We get the canvas element with document.querySelector .

And then we call getContext to get the context object.

Next, we create an image element with the Image constructor to create an image.

We set the src property to the URL of the image.

And then we set the baseImage.onload property to a function that calls context.drawImage with baseImage and the x and y coordinates of the top left corner.

Conclusion

We can add an image to the canvas with the drawImage method.

Leave a Reply

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