Take screenshot of webpage with Html2Canvas

Html2Canvas is a JavaScript library that provides the functionality to take a screenshot of the whole web page or a specific part.

It technically doesn’t take the screenshot but creates the view based on the available information on the page.

This returns HTML5 canvas element which you can use to show screenshot preview on the screen or create a new image file.

Take screenshot of webpage with Html2Canvas


Contents

  1. Download and Include
  2. Initialize
  3. Example 1
  4. Example 2
  5. Example 3 – Save to server
  6. Conclusion

1. Download and Include

  • Download the library from GitHub.
  • Include html2canvas.js script at the <head>.
<script type="text/javascript" src="html2canvas-master/dist/html2canvas.js"></script>

2. Initialize

Call html2canvas() method which takes selector as a parameter and with then handle canvas response.

html2canvas(document.body).then(function(canvas) {
 document.body.appendChild(canvas);
});

canvas.toDataURL()

This method returns the base64 value which you can use create image source or an image file.

html2canvas(document.getElementById('container')).then(function(canvas) {
 document.getElementById("image").src= canvas.toDataURL();
});

3. Example 1

Take the screenshot of the whole web page and show preview.

Completed Code

<!doctype html>
<html>
 <head>
  <script type="text/javascript" src="html2canvas-master/dist/html2canvas.js"></script>
 </head>
 <body>
  <h1>Take screenshot of webpage with html2canvas</h1>
  <div class="container" id='container' >
   <img src='images/image1.jpg' width='100' height='100'>
   <img src='images/image2.jpg' width='100' height='100'>
   <img src='images/image3.jpg' width='100' height='100'>
  </div>
  <input type='button' id='but_screenshot' value='Take screenshot' onclick='screenshot();'><br/>

  <!-- Script -->
  <script type='text/javascript'>
  function screenshot(){
    html2canvas(document.body).then(function(canvas) {
    document.body.appendChild(canvas);
   });
  }
  </script>

 </body>
</html>

4. Example 2

In this example, I am taking the screenshot of <div id='container'> content.

Completed Code

<!doctype html>
<html>
 <head>
  <script type="text/javascript" src="html2canvas-master/dist/html2canvas.js"></script>
 </head>
 <body>
  <h1>Take screenshot of webpage with html2canvas</h1>
  <div class="container" id='container' >
   <img src='images/image1.jpg' width='100' height='100'>
   <img src='images/image2.jpg' width='100' height='100'>
   <img src='images/image3.jpg' width='100' height='100'>
  </div>
  <input type='button' id='but_screenshot' value='Take screenshot' onclick='screenshot();'><br/>

  <!-- Script -->
  <script type='text/javascript'>
  function screenshot(){
   html2canvas(document.getElementById('container')).then(function(canvas) {
    document.body.appendChild(canvas);
   });
  }
  </script>

 </body>
</html>

5. Example 3 – Save to server

HTML & Script –

Create a similar HTML layout as above example.

Include the jQuery library.

Create screenshot() function where initialize html2canvas on body. By default, html2canvas set the image background color to black if save the screenshot.

With the use of background: '#fff' set background white.

Get taken screenshot image base64 URL using canvas.toDataURL().

Send AJAX request to save it to the server where pass base64URL variable as data.

<!doctype html>
<html>
  <head>
    <script type="text/javascript" src="html2canvas-master/dist/html2canvas.js"></script>
  </head>
  <body>
    <h1>Take screenshot of webpage with html2canvas</h1>
    <div class="container" id='container' >
      <img src='images/image1.jpg' width='100' height='100'>
      <img src='images/image2.jpg' width='100' height='100'>
      <img src='images/image3.jpg' width='100' height='100'>
    </div><br/>
    <input type='button' id='but_screenshot' value='Take screenshot' onclick='screenshot();'><br/>
    
    <!-- Script -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

     <script type='text/javascript'>
     function screenshot(){
        html2canvas(document.body,{background: '#fff'}).then(function(canvas) {

         document.body.appendChild(canvas);

         // Get base64URL
         var base64URL = canvas.toDataURL('image/jpeg').replace('image/jpeg', 'image/octet-stream');

         // AJAX request
         $.ajax({
            url: 'ajaxfile.php',
            type: 'post',
            data: {image: base64URL},
            success: function(data){
               console.log('Upload successfully');
            }
         });
       });  
     }
     </script>
  </body>
</html>

AJAX file –

Create a new ajaxfile.php file and upload directory to store the image.

Read $_POST['image'] value and specify upload path in $location.

Explode $image by ";base64," and decode base64 value using base64_decode().

Create a unique filename and use file_put_contets() to store file.

<?php 
$image = $_POST['image'];

$location = "upload/";

$image_parts = explode(";base64,", $image);

$image_base64 = base64_decode($image_parts[1]);

$filename = "screenshot_".uniqid().'.png';

$file = $location . $filename;

file_put_contents($file, $image_base64);

6. Conclusion

This plugin allows us to take the screenshot on the client browser without server-side interaction.

It might not able to generate the proper view if there is complex CSS applied to the elements.

Browser compatibility –

  • Firefox 3.5+
  • Google Chrome
  • Opera 12+
  • IE9+
  • Safari 6+
If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

91 thoughts on “Take screenshot of webpage with Html2Canvas”

  1. This example is really good.
    One quick requirement, Instead of appending to body. Is it possible to download from browser as image.

    Reply
    • Update screenshot() function –

      function screenshot(){
      html2canvas(document.body).then(function(canvas) {

      document.body.appendChild(canvas);
      var a = document.createElement(‘a’);
      a.href = canvas.toDataURL(“image/jpeg”).replace(“image/jpeg”, “image/octet-stream”);
      a.download = ‘image.jpg’;
      a.click();
      });
      }

      Reply
      • Hi Yogesh, first of all, thanks for share!! It’s great and I was looking for it

        Howeaver I need your help with something… It’s possible to open the image in a new tab or window? Or… its possible to print it (like open the printer window)?

        This 2 options would be great if its possible.

        Thanks!

      • Hi Claudio,
        You need to save the screenshot image to the server and use it to create link for preview in your page. For this use canvas.toDataURL() which gives you base64 url. With the use of AJAX save it to the server and return the image url.

      • Hi Yogesh,
        Tutorial is good. But just of curiocity. Does this library captures Dynamically generated Charts or text.

  2. can you please made an example on how to display the screenshot in a modal?
    and how can we display multiple screenshots on a carousal ?
    #bootstrap

    Reply
  3. i used this in my materialize css form, the screen shot in form is not good, maybe because of materialize css, and the rest is good

    function saveCanvas(id){
    html2canvas(document.getElementById(id)).then(canvas => {
    var imageData = canvas.toDataURL(‘image/jpeg’);
    var url = ‘my-api-url/images’;
    /* save image to server */
    $.ajax({
    url: url,
    type: ‘POST’,
    dataType: ‘text’,
    data: { myparams: imageData},
    success: function(response){
    console.log(response)
    }
    })
    })
    }

    Reply
  4. First of all, thank you Yogesh for the article. I am building an intranet for my organization and had faced a challenge on how to export a div element that displays the employee payslip details with the css styles intact. I tried server side PDF generation techniques but the styling was ugly, damn ugly. I then stumbled upon your blog and it helped me immensely. I ended up converting the div content to a png image and then downloaded it as pdf file

    Reply
  5. Hi Yogesh,

    I am done with the save screenshot step which is downloading an image to download folder. But how can I save the SS to a specific path of in my local directory.

    Reply
  6. Hello,

    This is great stuff and it worked but unfortunately it’s not getting the iframe part when the page got an iframe in it. What’s the workaround for this? Thanks.

    Reply
  7. Using example 3, it would be possible to show the image URL (localhost / upload / name_image.png), you just need to show the URL on the image screen that the user just created! Any help would be greatly appreciated! Thank you!

    Reply
  8. hi, can you give me complete ajaxfile.php example, please? i’m not able to make upload function working alone… thanks 😉

    Reply
  9. Thanks very much for this. Works really well for me.
    Saving the file to the server but I had to modify the php file so it saved as jpg, not png as irfanview said it was not a png file but jpg.
    I have a couple of things I need to do.
    1. I do not wish to see preview. How do I hide this?
    2. How do I get file name to be the value in drop down list?
    Thanks again. Love it.

    Reply
      • Many thanks. Preview is now not showing 🙂
        Not sure what you mean by “To get file name return $filename from AJAX file.”
        My php knowledge is next to none.
        So I have to chnage the ajax file to something like:
        $filename = “datepicker.’.jpg’;
        where datepicker is the id of the text input box.

      • I think this is much more complicated than I thought 🙁
        Cannot pass the value name=”datepicker” so easily. Something to do with js being client side and php being server side. Even posted code to stackoverflow and no-one there has been able to sort it.

  10. I have now resolved this. I had to update the screenshot function to include the following line (where datepicker is the ID from the text input box):
    var val1 = $(‘#datepicker’).val();

    Then update the ajax data code to the following:
    data: {image: base64URL, datepicker: val1},

    Finally I had to update the filename code in the php to:
    $filename = $_POST[‘datepicker’].’.jpg’;

    Reply
  11. HIi,
    I commented in this forum. But somehow could not see in the above list.
    Is it possible to take screenshot of dynamically generated Chart or content using html2canvas because i am not getting desired result.
    I am using reactjs and recharts for generating charts from content received via axios from server.

    -Arun

    Reply
  12. Hello,
    I’am trying to integrate this with angular. Can you provide your insights on that and also how can I make so that the captured image takes up entire screen and then I can perform operations on it like putting markers on it. It will be great help!!
    Thanks in advance.

    Reply
  13. Could someone please show a working example of return of $filename I can not seem to get it to work … it displays image but i need a URL of image that has been uploaded.

    Reply
  14. Hi
    Thanks for the cool stuff. I did everything according to example 3 and everything works, but the saved image on the server always has a black background. Preview of the saved DIV is fine, even as it saves the DIV preview to disk via the right mouse button (save image as), everything is also ok. Some hint what may be wrong

    Reply
  15. Good day!
    I went through your blog right now and I am amazed really! You have elaborated your article greatly with precise code and content.

    I have implemented this tutorial and it really works. Thanks Yogesh!

    Reply
  16. Hi, thanks for the code. I like the ajax way of doing this much better! I had an older html2canvas script that was saving a single image.

    Now, I’m saving an image and using the date and current time as the image name. I want to email this image every time it gets saved. My old script no longer works. Wondering if you’ve done this before?

    Basically — save image then send last saved image to “x” email.

    Thanks!

    Reply
      • Hi Fei,
        Yes, you can do that by redirecting to your new HTML page with a file path using JavaScript after file successfully saved. Read the passed file path to display the image.

  17. Hello and thank you for the article. I wanted to ask you if instead of showing the image or saving it to the server can Isend it by e-mail among other fields that the user enters?

    Thank you so much!

    Reply
  18. It is working all defined browser but my case it is not woring in IE any version of browsers can you give me suggestion for the same

    Reply
  19. This example is really good.
    Q1: I have targeted a container and downloaded the image. The image looks blurry. Unable to read the content. Is there any way to download it in high resolution.

    Q2: In landscape mode, the visible part of the container is downloaded instead of full. Is there any solution to this.

    Used code:
    function capture(){
    html2canvas(document.getElementById(‘profileBox’)).then(function(canvas) {

    document.body.appendChild(canvas);
    var a = document.createElement(‘a’);
    a.href = canvas.toDataURL(“image/jpeg”).replace(“image/jpeg”, “image/octet-stream”);
    a.download = ‘SnackSelfie.jpg’;
    a.click();
    });
    }

    Reply
  20. I wanna take a snapshot of div with the full height now it’s only taking the SS as much size is visible in the screen. any solution?

    Reply
    • here’s my code..

      html2canvas(input)
      .then((canvas) => {
      const imgData = canvas.toDataURL(‘image/png’).replace(‘image/jpeg’, ‘image/octet-stream’);
      const pdf = new jsPDF();
      pdf.addImage(imgData, ‘PNG’, 0, 0);
      pdf.save(‘download.pdf’);
      });

      Reply
  21. here’s my code..

    html2canvas(input)
    .then((canvas) => {
    const imgData = canvas.toDataURL(‘image/png’).replace(‘image/jpeg’, ‘image/octet-stream’);
    const pdf = new jsPDF();
    pdf.addImage(imgData, ‘PNG’, 0, 0);
    pdf.save(‘download.pdf’);
    });

    Reply
  22. Hello! thanks for answering:

    I have a web page (my site.html) and I want to generate a web page (my site screenshot.html) where I take a screen from the first web page.
    should i use getsceen and an iframeload?
    thanks!

    Reply
  23. var img = canvas.toDataURL(“image/jpeg”);
    This some times returns incomplete data, captured image returned is incomplete.
    Is there a way that we can check if the image is complete?
    NEED: I want to send that variable img to another function in same java script file which further sends that image over email.
    PROBLEM: it returns incomplete data many of the times, that the screenshot is incomplete, or we can say that empty screenshot or blank screenshot

    Reply
  24. Hi Yogesh,

    Thanks for the article.
    I want to take snapshot of a page which contains data and a scrollable table. The snapshot should have all the data of page including data from the scrollable table.

    Reply
    • function capture(){
      window.scrollTo(0, 0);
      html2canvas(document.getElementById(‘container’),{ height: document.getElementById(‘container’).scrollHeight}).then(function(canvas) {
      // Get base64URL
      var base64URL = canvas.toDataURL(‘image/jpeg’).replace(‘image/jpeg’, ‘image/octet-stream’);

      // AJAX request
      $.ajax({
      url: ‘test.php’,
      type: ‘post’,
      data: {image: base64URL},
      success: function(data){
      console.log(‘message);
      }
      });
      });
      }

      You can calculate the scroll height and add use it with heigh property. May this will help you

      Reply
  25. Hey, Yogesh I downloaded the same example that you are describing but it does not take a screenshot of the image can you please help me in this?

    Thanks in Advance

    Reply
  26. Hi ~ thanks for giving such wonderful tutorial, it’s really understandable! I just wonder can I apply this technique to another site which not owned by myself. Take screenshot from anysite I want…is it possible….? thanks for teaching …:)

    Reply
  27. Hi Yogesh,
    Thanks for the example, currently I am facing a problem in html2canvas I am using html2canvas screenshot for dynamic data. It works fine for first iteration andfrom second iteration I am getting blank screen

    Can you help me please

    Reply
  28. Hi Yogesh,
    you are doing an amazing work making the code and documentation part easy for otherr to understand. How can i download the same screenshot in my local on click.

    Reply
  29. Was searching for a week. This one is the simplest solution I could find. how can we do this instead of specifying div, giving certain screen co-ordinates?

    Reply

Leave a Comment