How to Convert HTML to Image in JavaScript

Shubham Vora Feb 02, 2024
  1. Use the html2canvas JavaScript Library to Convert HTML to Image
  2. Use the dom-to-image JavaScript Library to Convert HTML to Image
How to Convert HTML to Image in JavaScript

We will learn to render the HTML as an image in this article. It means we will take the 2D snapshot of the web page, which contains HTML, and display it on the webpage or download the image.

We have used external JavaScript libraries to render HTML to images in the below methods.

Use the html2canvas JavaScript Library to Convert HTML to Image

We have used the html2canvas library in the below example to convert HTML to an image and render it on the web page.

For example, we created two div elements with different ids, my-div and ShowImage. We will take the snapshot of the div element with the my-div id and display the snapshot inside the div element with the id ShowImage.

Also, we have created the <button> element and added the onclick event for that. When the user clicks on the button, it will call the convertToImage() function, which will convert HTML to image.

<body>
    <div id="my-div">This is sample div element.</div>
    <div id="ShowImage"></div>
    <button onclick="convertToImage()">Convert</button>
</body>

We have applied some styles to the div elements in the CSS below. We have set the height, width, and background-color for the div elements using CSS properties.

Also, we set the margin for all div elements to leave some space around.

div {
    display: block;
    margin: 20px;
}
#my-div {
    height: 300px;
    width: 300px;
    background-color: red;
}

To use the html2canvas library, users need to download it to their local computer from (https://html2canvas.hertzen.com/). After that, users can add the library to the HTML code via the <script> tag by assigning the right path of the library file to the src attribute of the <script> tag.

<script src="html2canvas.js" type="text/javascript"></script>

The convertToImage() function contains the JavaScript code to convert the HTML to image.

In the below example code, we have accessed the div element with the id my-div using their id in JavaScript and applied the html2canvas function to capture the image of that particular HTML element. The canvas will store the image, and we have appended that image to the div element with the id ShowImage.

<script>
    function convertToImage() {
        html2canvas(document.getElementById("my-div")).then(function (canvas) {
        document.getElementById("ShowImage").appendChild(canvas);
        });
    }
</script>

Output:

convert html to image - one

In the above output animation, users can see that when we click on the convert button, it will render the new image of the <div> element inside the document body.

Furthermore, we can create the HTML link to download and save the captured image locally.

Here, we have created the new <a> element using document.createElement("a"), and stored it inside the anchor variable. Also, we have appended the <a> element to the document body using document.body.appendChild(anchor).

Next, we have given the name to the downloadable image file using anchor.download = "sample.jpg", and set the href attribute for the anchor using the toDataURL property of the canvas variable. Also, we have set the _blank value for the target attribute of anchor to make the image downloadable.

The output also shows that when we click on the convert button, it appends the image of the div element to the web page and downloads the same image file to the local computer.

<script>
    function convertToImage() {
        html2canvas(document.getElementById("my-div")).then(function (canvas) {
        var anchor = document.createElement("a");
        document.body.appendChild(anchor);
        document.getElementById("ShowImage").appendChild(canvas);
        anchor.download = "sample.jpg";
        anchor.href = canvas.toDataURL();
        anchor.target = "_blank";
        anchor.click();
       });
    }
</script>

Output:

convert html to image - two

Use the dom-to-image JavaScript Library to Convert HTML to Image

The below HTML code is almost the same as the one used in the above example, which contains two div elements with different values of the id attribute.

<div id="my-div">Demo texts.</div>
<div id="ShowImage"></div>
<button onclick="convertToImage()">Convert to image</button>

The below CSS code contains the styling for the HTML code, and it is almost the same as we have used inside the above example code.

div {
    display: block;
    margin: 20px;
}
#my-div {
    height: 100px;
    width: 100px;
    background-color: blue;
}

To use the domtoimage library, we have to download it locally, or we can use its CDN. Here, users need to embed the below CDN of the domtoimage library in the <head> section of the HTML code.

<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"
      referrerpolicy="no-referrer"
    ></script>

In the below JavaScript code, we have accessed the div element using its id and stored it in the element variable.

Next, we used the domtoimage library to convert the HTML to a png image. We have created the new empty image using the new Image() constructor and stored it inside the newImage variable.

Also, we are assigning the URL value to the src attribute of the newImage variable. After that, we are appending the newImage to the web page.

Also, we have used the catch block to handle the errors.

<script>
    function convertToImage(){
    var element = document.getElementById("my-div");
    domtoimage
        .toPng(element)
        .then(function (URL) {
            var newImg = new Image();
            newImg.src = URL;
            document.getElementById('ShowImage').appendChild(newImg);
        })
        .catch(function (error) {
            console.error("error");
        });
    }
</script>

Output:

convert html to image - three

Users can observe that we are taking the snapshot of the blue div; whenever we click on the button, our code will append a new snapshot of the blue div to the document body.

Author: Shubham Vora
Shubham Vora avatar Shubham Vora avatar

Shubham is a software developer interested in learning and writing about various technologies. He loves to help people by sharing vast knowledge about modern technologies via different platforms such as the DelftStack.com website.

LinkedIn GitHub

Related Article - HTML Image

Related Article - HTML Convert