How to draw an image from a data URL to a canvas with JavaScript?

Spread the love

Sometimes, we want to draw an image from a data URL to a canvas with JavaScript.

In this article, we’ll look at how to draw an image from a data URL to a canvas with JavaScript.

How to draw an image from a data URL to a canvas with JavaScript?

To draw an image from a data URL to a canvas with JavaScript, we call the drawImage method.

For instance, we write

const myCanvas = document.getElementById("my_canvas_id");
const ctx = myCanvas.getContext("2d");
const img = new Image();
img.onload = () => {
  ctx.drawImage(img, 0, 0);
};
img.src = strDataURI;

to get the canvas with getElementById.

Then we get the context with getContext.

Next we create an img element with the Image constructor.

We set its onload property to a function that calls drawImage to draw the img element onto the canvas when the image is loaded.

Then we set img.src to a string with the image URL to load the image.

Conclusion

To draw an image from a data URL to a canvas with JavaScript, we call the drawImage method.

Leave a Reply

Your email address will not be published.