How To Use Html2Canvas JavaScript Library

In the world of web development, we often desire to create a feature for capturing screenshots of specific elements within web pages. For instance, we might want to visually showcase a web page's appearance to share captivating content on social media, generate reports with dynamically arranged page elements, or even enable users to save data visualizations as image files.

However, capturing screenshots of HTML elements is not an easy task to accomplish with pure JavaScript. Standard screenshot methods, like "Print Screen," can only capture the entire screen and not specific elements. To address this challenge, enter HTML2Canvas, a JavaScript library that allows us to capture screenshots of elements within web pages and convert them into PNG images.

Html2Canvas

HTML2Canvas is a powerful and versatile tool that leverages HTML canvas technology to temporarily redraw targeted elements on a canvas. By replicating the desired elements and rendering them on a canvas, HTML2Canvas then retrieves data from the canvas and converts it into a PNG image. This way, it enables us to easily capture screenshots of elements that would otherwise be challenging to obtain using standard screenshot methods.

You can visit the official website html2canvas.com to see its documentation and in this article, the author will teach you how to use this JavaScript library easily and simply so that you can understand it. The author will also teach how to take a screenshot and save the screenshot results. let's start the tutorial now!

Tutorial

  1. First, create a folder named html2canvas-js to facilitate our tutorial.
  2. Open your IDE.
  3. And then create index.html file and save into html2canvas-js folder.
  4. Here is the code :
  5. <!DOCTYPE html>
    <html>
      <head>
        <title>HTML2Canvas Screenshots Example</title>
      </head>
    
      <body>
        <h2>Example of Using HTML2Canvas for Screenshots</h2>
    
        <div id="target-element-1">
          <!-- The first element to be captured as a screenshot. -->
    
          <h4>**Cat Theme: First Target Element**</h4>
    
          <p>
            In the virtual world, there are adorable creatures that capture
            everyone's attention - cats! Cats are incredibly cute animals with
            unique behaviors. The first target element presents a tempting message
            to capture screenshots of sweet moments related to cats.
          </p>
    
          <p>
            Whether your cat is peacefully sleeping on a soft bed or perhaps playing
            with an unexpected ball of yarn, these moments deserve to be captured as
            unforgettable memories. With the help of the HTML2Canvas library, we can
            easily capture these cute cat moments and convert them into high quality
            PNG images.
          </p>
    
          <p>
            Not only for personal enjoyment, these adorable cat images can also
            bring joy to others. You can share these screenshots on social media,
            where cute cat pictures always receive lots of attention and affection
            from friends and fellow cat enthusiasts.
          </p>
    
          <p>
            So, what are you waiting for? Let's capture screenshots of these sweet
            and adorable cat moments! With the HTML2Canvas library, you will be able
            to effortlessly create an unforgettable collection of cat images that
            can warm the hearts of everyone who sees them.
          </p>
        </div>
    
        <div id="target-element-2">
          <!-- The second element to be captured as a screenshot -->
    
          <h4>**Cow Theme: Second Target Element**</h4>
    
          <p>
            In addition to cats, there is another creature with its own unique charm
            - cows! Cows are known for their simplicity and distinctive appeal. The
            second target element provides an opportunity to capture interesting
            moments related to cows in the form of screenshots.
          </p>
    
          <p>
            Whether you have adorable pictures of cows strolling in green meadows or
            enjoying companionship with their friends at the farm, these images are
            precious memories worth capturing. With the help of the HTML2Canvas
            library, you can easily take screenshots of these beautiful moments and
            save them as high-quality PNG files.
          </p>
    
          <p>
            The screenshots of these cow moments will not only be a valuable
            personal collection but also can be shared to inspire others. Convey
            positive messages through images of calm and peaceful cows, or showcase
            the endearing side of these gentle creatures to your friends and family.
          </p>
    
          <p>
            Furthermore, these captivating cow images can be used as decorative
            elements in design projects or as engaging illustrations in your reports
            or presentations. By capturing screenshots of this element using the
            HTML2Canvas library, you will have access to high-quality cow images to
            use according to your needs.
          </p>
    
          <p>
            So, don't miss the opportunity to capture beautiful and tranquil moments
            related to cows. Come on, take a screenshot and let these cow images
            bring warmth and serenity to your life and to others who see them.
          </p>
        </div>
    
        <button id="btn">Take Screenshots</button>
    
        <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
        <script src="script.js"></script>
      </body>
    </html>

  6. Result :
  7. For javascript file you need to create script.js file and don't forget to save into html2canvas-js folder.
  8. Here is the javascript code :
  9. function captureScreenshot(targetElementId, fileName) {
      const captureElement = document.querySelector(targetElementId);
    
      html2canvas(captureElement)
        .then((canvas) => {
          canvas.style.display = "none";
          document.body.appendChild(canvas);
          return canvas;
        })
        .then((canvas) => {
          const image = canvas.toDataURL("image/png");
          const a = document.createElement("a");
          a.setAttribute("download", fileName);
          a.setAttribute("href", image);
          a.click();
          canvas.remove();
        });
    }
    
    const btn = document.querySelector("#btn");
    btn.addEventListener("click", () => {
      captureScreenshot("#target-element-1", "my-screenshot1.png");
      captureScreenshot("#target-element-2", "my-screenshot2.png");
    });

    Let's break down the code step by step:

    Function to Capture Screenshot:
    function captureScreenshot(targetElementId, fileName) {
      const captureElement = document.querySelector(targetElementId);
    
      html2canvas(captureElement)
        .then((canvas) => {
          canvas.style.display = "none";
          document.body.appendChild(canvas);
          return canvas;
        })
        .then((canvas) => {
          const image = canvas.toDataURL("image/png");
          const a = document.createElement("a");
          a.setAttribute("download", fileName);
          a.setAttribute("href", image);
          a.click();
          canvas.remove();
        });
    }

    - The captureScreenshot function takes two parameters targetElementId (string) and fileName (string). It captures the screenshot of the HTML element with the specified targetElementId and saves it with the provided fileName.

    - It starts by selecting the element to capture using document.querySelector(targetElementId) and stores it in the captureElement variable.

    - The html2canvas() function is used to capture the element as a canvas. It returns a Promise that resolves to the canvas element.

    - In the first .then() block, the captured canvas is appended to the document body (hidden from view) to access its data URL later.

    - In the second .then() block, the data URL of the canvas is obtained using canvas.toDataURL("image/png").

    - A new a (anchor) element is created to download the screenshot. The download attribute is set to fileName, and the href attribute is set to the data URL of the canvas.

    - The anchor element is clicked programmatically (a.click()) to initiate the download of the screenshot.

    - Finally, the appended canvas is removed from the document.

    Event Listener for the Button:
    const btn = document.querySelector("#btn");
    btn.addEventListener("click", () => {
      captureScreenshot("#target-element-1", "my-screenshot1.png");
      captureScreenshot("#target-element-2", "my-screenshot2.png");
    });

    - The code selects a button element with the id "btn" and stores it in the btn variable.

    - An event listener is added to the button using btn.addEventListener("click", () => { ... }).

    - When the button is clicked, the callback function is executed, and it calls the captureScreenshot function twice.

    - The first call captures the screenshot of the HTML element with the id "target-element-1" and saves it as "my-screenshot1.png".

    - The second call captures the screenshot of the HTML element with the id "target-element-2" and saves it as "my-screenshot2.png".

    In summary, the JavaScript code provided defines a function captureScreenshot() to capture screenshots of specified HTML elements using the html2canvas library. It then attaches an event listener to a button, and when clicked, it captures screenshots of two different HTML elements and saves them as PNG images with specified filenames.

  10. Several results when the author presses the take screenshots button :
  11. - Screenshot one

    - Screenshot two

Closing

Of course, with the capabilities of HTML2Canvas, we must also always remember to respect copyright and privacy, and use screenshots wisely in accordance with applicable rules and ethics. We hope this article has provided a helpful guide for you to understand and use HTML2Canvas for taking screenshots in web development. With creativity and the right knowledge, you can create captivating and meaningful screenshots. Happy experimenting and creating with HTML2Canvas to capture screenshots of your web pages!