Sometimes, we may want to render an HTML document or node to an image with JavaScript.
In this article, we’ll look at how to render an HTML document or node to an image with JavaScript.
Use the dom-to-image Library
The dom-to-image library makes converting an HTML node to an image easily.
For instance, if we have the following HTML:
<table>
<tr>
<td>col1 Val1</td>
<td>col2 Val2</td>
</tr>
<tr>
<td>col1 Val3</td>
<td>col2 Val4</td>
</tr>
</table>
<div>
</div>
Then we can add the library with the following script tag:
<script src="https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js" integrity="sha512-01CJ9/g7e8cUmY0DFTMcUw/ikS799FHiOA0eyHsUWfOetgbx/t6oV4otQ5zXKQyIrQGTHSmRVPIgrgLcZi/WMA==" crossorigin="anonymous"></script>
Or we can add the library with NPM:
npm install dom-to-image
or Bower:
bower install dom-to-image
Then we can use it by writing the following JavaScript:
const table = document.querySelector("table");
const div = document.querySelector("div");
domtoimage.toPng(table)
.then((dataUrl) => {
const img = new Image();
img.src = dataUrl;
div.appendChild(img);
})
.catch((error) => {
console.error(error);
});
We call domtoimage.toPng
with the element that we want to render to an image.
Then we get the dataUrl
, which is the base64 string version of the image of the rendered element.
In the then
callback, we create a new img
element with the Image
constructor.
Then we set the src
property of it to dataUrl
.
And then we call div.appendChild
with img
to append img
to the div.
We can simplify this by using the async
and await
syntax:
const table = document.querySelector("table");
const div = document.querySelector("div");
(async () => {
try {
const dataUrl = await domtoimage.toPng(table)
const img = new Image();
img.src = dataUrl;
div.appendChild(img);
} catch (error) {
console.error(error);
}
})()
dataUrl
is the same one as the then
method callback parameter.
error
is the same one as the one in the catch
method callback parameter.
Conclusion
The dom-to-image Library lets us render an HTML node to an image easily with JavaScript.