How to convert base64 PNG data to HTML5 canvas with JavaScript?

Spread the love

Sometimes, we want to convert base64 PNG data to HTML5 canvas with JavaScript.

In this article, we’ll look at how to convert base64 PNG data to HTML5 canvas with JavaScript.

How to convert base64 PNG data to HTML5 canvas with JavaScript?

To convert base64 PNG data to HTML5 canvas with JavaScript, we call drawImage.

For instance, we write

<canvas id="c"></canvas>

to add a canvas element.

Then we write

const canvas = document.getElementById("c");
const ctx = canvas.getContext("2d");

const image = new Image();
image.onload = () => {
  ctx.drawImage(image, 0, 0);
};
image.src =
  "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";

to get the canvas with getElementById.

Then we get its 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 image into the canvas.

And then we set the src property to trigger onload to be called.

Conclusion

To convert base64 PNG data to HTML5 canvas with JavaScript, we call drawImage.

Leave a Reply

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