How to render HTML to an image with JavaScript?

Spread the love

Sometimes, we want to render HTML to an image with JavaScript.

In this article, we’ll look at how to render HTML to an image with JavaScript.

How to render HTML to an image with JavaScript?

To render HTML to an image with JavaScript, we use the dom-to-image library.

To install it, we run

npm install dom-to-image

Then we use it by writing

import domtoimage from "dom-to-image";

const node = document.getElementById("my-node");
const dataUrl = await domtoimage.toPng(node);
const img = new Image();
img.src = dataUrl;
document.body.appendChild(img);

to select the node to render to an image with getElementById.

Then we call domtoimage.toPng to render the node to an image.

Next, we create an img element with the Image constructor.

We set its src property to the dataUrl returned by the promise.

And then we append img to the body with appendChild.

Conclusion

To render HTML to an image with JavaScript, we use the dom-to-image library.

Leave a Reply

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