How to Convert HTML to Image with JavaScript

This article explains how to convert a div to an image in JavaScript. Yes, we are going to generate an image from our HTML page on the client side. All we need HTML tag, and using the html2canvas javascript library we can create images .i.e converting the HTML table to Image PNG, JPG, or converting DIV, UL, and LI tags into Jpg image format.

Now let’s head towards the coding part and see how we can convert HTML to Picture.

Step to render HTML to Image

  • Download and import HTML2Canvas jquery files.
  • Add HTML markup.
  • JavaScript Code to convert HTML div to Image [png]

First, we need to download and import the latest jquery library on our web page. You can import your server-hosted jQuery file or use it from the Google-hosted site (recommended).

For converting HTML to Image, we need to import one more javascript library, and it is HTML2CANVAS download it and import it into the HTML head tag.

Now we are done with downloading, so our final head tag looks as shown below.

<script src="scripts/jquer_latest_3.6_.min.js" type="text/javascript"></script>
<script src="scripts/html2canvas.js" type="text/javascript"></script>

Note: If you want to use only javascript, then no need to import the jQuery library. All you need to follow are Steps 2 and Step 3.

Add HTML markup 

Let’s make this article very simple, so now am adding some dummy HTML form elements i.e. form tags, but you can add dynamic HTML using jQuery ajax for which you want to generate images.

<script src="https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"></script>
<form>
  <label>First Name:</label><br>
  <input id="fname" name="fname" value="Muhammad"><br>
  <label>Last Name:</label><br>
  <input type="text" id="lname" name="lname" value="Rauf"><br><br>
  <input type="submit" value="Submit">
</form> 
<div>
</div>

JavaScript Code:

<script>
const form = document.querySelector("form");
const div = document.querySelector("div");
domtoimage.toPng(form)
  .then((dataUrl) => {
    const img = new Image();
    img.src = dataUrl;
    div.appendChild(img);
  })
  .catch((error) => {
    console.error(error);
  });
  </script>

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, then callback, we create a new img element with the Image constructor.

We set the src property of it to dataUrl . And then we call div.appendChild with img to append img to the div.

Convert HTML to Image with a Download button

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<div id="form">     
<h1>This block will be converted to image</h1>
    </div>
    <input id="View" type="button" value="Preview"/>
    <a id="button" href="#">Download</a>
    <br/>
    <h3>Preview :</h3>
    <div id="preview">
    </div>

JavaScript Code:

<script>
$(document).ready(function(){
var element = $("#form"); // global variable
var getCanvas; // global variable
    $("#View").on('click', function () {
         html2canvas(element, {
         onrendered: function (canvas) {
                $("#preview").append(canvas);
                getCanvas = canvas;
             }         });    });

	$("#button").on('click', function () {
    var imgageData = getCanvas.toDataURL("image/png");
    var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream");
    $("#button").attr("download", "your_pic_name.png").attr("href", newData);
	});
});
</script>

Certainly! Here’s a full working example with code that demonstrates how to convert HTML to image with JavaScript using the html2canvas library:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>HTML to Image with JavaScript</title>
    <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
  </head>
  <body>
    <div id="my-element">
      <h1>Hello, world!</h1>
      <p>This is some sample text that will be converted to an image.</p>
      <ul>
        <li>softcodeon 1</li>
        <li>softcodeon 2</li>
        <li>softcodeon 3</li>
      </ul>
      <img src="https://picsum.photos/200/300" alt="Random Image">
    </div>

    <canvas id="my-canvas"></canvas>
    <button onclick="saveImage()">Save Image</button>

    <script>
      function saveImage() {
        const element = document.getElementById("my-element");
        const canvas = document.getElementById("my-canvas");

        html2canvas(element).then(function(canvas) {
          const dataURL = canvas.toDataURL();
          const link = document.createElement("a");
          link.download = "image.png";
          link.href = dataURL;
          link.click();
        });
      }
    </script>
  </body>
</html>

In this example, we have a simple HTML document with a div element containing some sample content that we want to convert to an image. We’ve also added a canvas element that will be used to render the HTML and a button element that will trigger the image download.

The saveImage() function is called when the button is clicked. This function retrieves the HTML element to be converted and the canvas element to be used for rendering. It then uses the html2canvas library to render the HTML onto the canvas, converts the canvas to a data URL, creates a new link element with the download attribute set to the desired filename and the href attribute set to the data URL, and programmatically clicks the link to trigger the image download.

You can customize this example by replacing the sample HTML content with your own content, and by modifying the saveImage() function to suit your needs.

Conclusion

Here’s an easy way to render HTML to an image like PNG. As it’s easy to create an image from a canvas. But to render standard HTML elements like Form, UL, LI, Table, and P tags to an image we use the HTML2Canvas javascript library. Using HTML2Canvas will take screenshots of our HTML web pages. I personally found this as the best javascript library to convert HTML to images.

Leave a Comment

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

Scroll to Top