Categories
JavaScript Answers

How to get image from canvas element and use it in img src tag with JavaScript?

Spread the love

Sometimes, we want to get image from canvas element and use it in img src tag with JavaScript.

In this article, we’ll look at how to get image from canvas element and use it in img src tag with JavaScript.

How to get image from canvas element and use it in img src tag with JavaScript?

To get image from canvas element and use it in img src tag with JavaScript, we can use the canvas toDataURL method.

For instance, we write

const image = new Image();
image.id = "pic";
image.src = canvas.toDataURL();
document.getElementById("image-for-crop").appendChild(image);

to call canas.toDataURL to return the canvas image a base64 URL string.

Then we set its as the src attribute value of the image img element to show the image in the base64 URL.

Conclusion

To get image from canvas element and use it in img src tag with JavaScript, we can use the canvas toDataURL method.

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 *