DEV Community

Cover image for Convert HTML to Image: A Step-by-Step Guide
Izzy-Loa
Izzy-Loa

Posted on

Convert HTML to Image: A Step-by-Step Guide

So, you want to turn the awesome HTML code you've made that's on your website and have a way to convert it into an image for you to save? Imagine saving your code into an image - how cool!

Well, look no further! I too wanted to do the same thing but funny enough, there weren't any straightforward tutorial out there that could show you how! After hours of searching, I finally discovered the solution and wanted to share it with you. So, whether you're still struggling or simply curious to see how I did it, read on and let's get started!

gif of a woman saying lets go


Set your environment

Before we dive into the conversion process, I'll assume you already have your HTML code ready. What you want to learn is how to turn it into an image file. You should have a good grasp of HTML and JavaScript. For this tutorial, we'll use the following HTML code example:

<body>
  <!-- HTML for the div with information -->
  <div class="info-div">
    <h2>Welcome to My Web Page</h2>
    <img src="dog.jpg" alt="dog image" />
    <p>Hello, I'm Izzy-Loa, a junior web developer based in Liverpool, UK. I'm currently sharing my coding progress on Tumblr and Twitter.</p>
  </div>

  <button>Click me</button>
  <script src="script.js"></script>
</body>
Enter fullscreen mode Exit fullscreen mode

We won't include the CSS code, as it doesn't affect this tutorial. The JavaScript file (<script src="script.js"></script>) at the bottom of the <body> is where we'll add the functionality for the conversion.

Your page should resemble the following:

what the example code renders to look like

As you can see, the "Click me" button (<button>Click me</button>) will handle the conversion. We aim to convert everything within the <div class="info-div">...</div> into an image.


Using the html2canvas JavaScript Library

The html2canvas library allows you to take screenshots of webpages and target specific elements on a screen. Here are the steps to include the library in your project:

The steps to put the library in your project:

  1. Visit the html2canvas website for more information.
  2. Copy the CDN link from here the cdn site where the link is and include it in a script tag in your project's head:
<head>
   <title>How to convert an HTML element or document into image?</title>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js" integrity="sha512-BNaRQnYJYiPSqHHDb58B0yaPfCu+Wgds8Gp/gU33kqBtgNS4tSPHuGibyoeqMV/TJlSKda6FXzoEyYGjTe+vXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
Enter fullscreen mode Exit fullscreen mode

That's it for including the library on the HTML side. Now, let's move on to the JavaScript code.


JavaScript Functionality

Here's the JavaScript code to handle the conversion:

const button = document.querySelector("button");
const div = document.querySelector(".info-div");

button.addEventListener("click", function () {

    html2canvas(div).then((canvas) => {
        const imageDataURL = canvas.toDataURL("image/png");

        // Create a download link for the image
        const a = document.createElement("a");
        a.href = imageDataURL;
        a.download = "dog.png";
        a.click();

    });

});
Enter fullscreen mode Exit fullscreen mode

In this code, I want to turn the whole <div class="info-div">...</div> into an image, I put it into a variable in const div = document.querySelector(".info-div");.

I also put the button into a variable in const button = document.querySelector("button");

I add a click event listener to the button so when the user clicks the button, it will follow the code inside of the event listener!

You can find similar code like this in the documentation of the html2canvas library:

html2canvas(div).then((canvas) => {
   const imageDataURL = canvas.toDataURL("image/png");

   // Create a download link for the image
   const a = document.createElement("a");
   a.href = imageDataURL;
   a.download = "dog.png";
   a.click();
});
Enter fullscreen mode Exit fullscreen mode

What is happening here is:

  1. We add the div (or what the element we want to take an image of) into the html2canvas([element]).then((canvas)
  2. Added the image file type url to a variable = const imageDataURL = canvas.toDataURL("image/png"); - You can replace the png to other image file types such as jpg, jpeg etc
  3. Created an anchor/link tag, added the href attribute to imageDataURL
  4. The download attribute is where we will give the default name the image file, I added "dog.png"
  5. Perform the click() function to the anchor tag so it starts to download the image we created

And that's it!


The End

And that's it! You've successfully learned how to turn your HTML into an image. It's a great way to save and share your web content in a unique format.

The whole process

If you have any questions or need further clarification, please feel free to ask. Enjoy converting your HTML into images!

Check out my other posts and links! 🙋🏾‍♀️💗

Top comments (1)

Collapse
 
jwrunge profile image
Jacob W Runge

Nicely done! This would make for a good context-aware screen grab feature.