Categories
JavaScript Answers

How to render HTML to an image with JavaScript?

Spread the love

To render HTML to an image with JavaScript, we use the html2canvas package.

To install it, we add the script tag with src pointing to https://html2canvas.hertzen.com/dist/html2canvas.min.js

Then we write

const canvas = await html2canvas(document.getElementById("image-wrap"));
const link = document.createElement("a");
document.body.appendChild(link);
link.download = "pic.jpg";
link.href = canvas.toDataURL();
link.target = "_blank";
link.click();

to select the element with getElementById.

And then we call html2canvas with the element.

We get the canvas from the returned promise with await.

Next we create a link with createElement.

We set the download property to the file name.

We call canvas.toDataURL to return the canvas content as a base64 URL string and set it as the value of the href property.

Then we call click to download the content.

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 *