html2canvas- Take Screenshot of Web Page and Save It to Server (Javascript and PHP)

html2canvas- Take Screenshot of Web Page and Save It to Server (Javascript and PHP)

March 1, 2013 8:05 pm 75 comments

FeedBack is important. Usually, end-users struggle to clarify their problems. And you might be unreachable for a phone call or remote connection.

That causes a huge need of visualization. First solution that appears in mind is to capture the current screen of user.

However, when I tried to implement that, it wasn’t so easy as I expected. Some old ways offer ActiveX but it seems too outdated. Since there’s a bridge needed between client side and server, JS libraries are the best way.

There’s a great library, html2canvas. It is told to be reverse-engineered version of Google Plus’ way of taking screenshots.

When I first discovered this library, it took me a while to use for simplest implementation. I just wanted to visualize a div element. However, there was no single page to tell the whole path to follow, thus I had to combine various sources.

Here’s how you can easily use for taking a screenshot of a div:

1- Import libraries
There are 3 libraries to import:

  • jquery.js
  • html2canvas.js
  • jquery.plugin.html2canvas.js

You can download html2canvas and html2canvas jQuery plugin from this link.
Note: The source link contains html2canvas v0.40. I recommend you to check for a newer version and use it instead from official html2canvas site.

I have used jquery.min.js v1.7.1 but you can try other versions. For this jQuery library, use this link.
Here’s first lines of code:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="js/html2canvas.js"></script>
<script type="text/javascript" src="js/jquery.plugin.html2canvas.js"></script>
<!-- -->

2- Create your div
In my code, I used html2canvas for a div. You can use the whole body tag instead, it’s up to you.
Attach a div element to the page with a certain id:

<div id="target">
<!-- Render your page inside of this div. -->
</div>

3- Create a button and a hidden form
This part is important. In order to save the image to server, we need to pass captured image data with a form field.
In 4th step, you’ll see JavaScript code that writes the image data to hidden field and posts the form.

<input type="submit" value="Take Screenshot Of Div" onclick="capture();" />
<form method="POST" enctype="multipart/form-data" action="save.php" id="myForm">
    <input type="hidden" name="img_val" id="img_val" value="" />
</form>

4- JavaScript Code

    function capture() {
        $('#target').html2canvas({
            onrendered: function (canvas) {
                //Set hidden field's value to image data (base-64 string)
                $('#img_val').val(canvas.toDataURL("image/png"));
                //Submit the form manually
                document.getElementById("myForm").submit();
            }
        });
    }

5- Use the posted values
Here I used a form to post the value. You can use Ajax calls or whatever. I have a PHP file, save.php. In this file, we will both show the picture and save it to the server.

//save.php code

//Show the image
echo '<img src="'.$_POST['img_val'].'" />';

//Get the base-64 string from data
$filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);

//Decode the string
$unencodedData=base64_decode($filteredData);

//Save the image
file_put_contents('img.png', $unencodedData);

6- Enjoy your day
So that’s pretty much it. Click here for a live demo or download the codes from Github repository page.

7- Notes

* This tutorial uses html2canvas v0.4.0 – 30.1.2013. It has a new release, v0.4.1 – 7.9.2013, can be downloaded from here. Though avaliability of newer versions haven’t been tested with the code above.

* Some people have declared that they had issues with checkbox/radiobutton states on the captured image. Stu has shared his code to capture these elements with their states. I haven’t tried by myself but people who face problem about this may get some opinion from his comment.

75 Comments

  • dhamodaran

    hi how to use html2canvas screenshot from asp.net

  • magnil

    Thanks for the brilliant work!You really save my day.
    I also get a question when using this.What should I do if I wanna take screenshot of web page from a given URL?

    For example,I would like to capture the http://www.w3schools.com . I tried to replace the content with a inline .This is what I got:http://xiaoxiaoyue.cn/html2canvas-basic/ . It shows the frame, but when I clicked on the button, nothing had captured expect a blank background.

    So what should I do? Sorry to trouble you and many thanks.

    • Hi,

      Sorry for the late response. I better check my e-mail notifications…

      Glad you could use it for your own purpose. I wish I could answer your question too but it might need a little bit more of research.

      Trying it with frames is a good idea, however, think of it from this way: When you use a frame, you actually connect to a remote server. What you have in your server is a blank frame so, html2canvas gives you exactly this.

      But good news is that we know it is possible with html2canvas, we just don’t know how. Please check the official test page, there you can see that you can give the URL and get the screenshot:
      http://html2canvas.hertzen.com/screenshots.html

      So I believe that what you want can be found in official examples and after you figure out how, you can use my code to save to the web server.

      Regards,

    • sudip

      you are right I am rtying to capture some image after loading a iframe, but it not working !!

  • magnil

    ^tried to replace the div content with a inline iframe

  • umesh gandhe

    anyone convert this save.php code in javascript.
    Because i don’t know the php.
    so want your help

    • I’m afraid I didn’t catch what you mean.

      PHP is a server-side language, JavaScript works in the client side. So there is no exact conversion.

      You need to use a server-side scripting language in order to save the image to the server, according to what language your server supports (whether PHP, Asp.NET, Python, Ruby etc.).

      But I don’t think you need to know PHP in order to use my sample code. Just download the project from Github and use it in a server that supports PHP. It’s easier than you think.

  • umesh gandhe

    So Kubilay can you convert this php code into asp.net.

  • umesh gandhe

    Hi,
    we have not access to download any tool .
    so can you convert it to asp.net, please.

    • create a save.aspx or .asp file

      change form action value to save.aspx

      and your save.aspx.cs sould like this:

      using System;
      using System.Collections.Generic;
      using System.Collections.Specialized;
      using System.Web;
      using System.Web.UI;
      using System.Web.UI.WebControls;

      public partial class save : System.Web.UI.Page
      {
      protected void Page_Load(object sender, EventArgs e)
      {
      NameValueCollection form = Request.Form;
      Response.Write(“”);
      }
      }

      u r welcome.

    • img src=’”+form["img_val"]+”‘ /

      inside of Response.Write(“”);

  • Cannot for the life of me get this working.

    I can get it to write an empty file if I move the form around the “target” div, but otherwise it does nothing.

    I have scoured your source code and see nothing different from what I have.

    • Hi,

      All I can offer is that you can download my repo from Github and modify the code according to your needs. Maybe you are missing a point in tutorial, try to go through the working code.

      Regards.

    • Clinton

      Check your browser – the script does not work in some (older) browsers. For example, I use Eclipse SDK and the software does rot run in the Eclipse php viewer but works fine in Firefox.

  • manoj

    how can i capture screenshot and save it to database in java spring

  • dev79

    I tried with html2canvas. But this stuff does not works in IE.

  • hello,
    before using it on my website, i wanted to try the method so i installed your demo on my website but it doesn’t seem to work…
    http://astridetvalerian.be/TEST/
    the image link is missing so i suppose it doesn’t save the image… i setted the CHMOD attributes of the folder on my server to 777, but it still doesn’t save the image…
    can you maybe help me?
    thaks in advance!

    • Hi,

      According to your PHP version and configuration, PHP might not show the errors though it should. First, try to see if there is any error, by using the code in this link: http://www.dzone.com/snippets/let-php-show-all-errors

      If there’s an error about file permissions or anything else, it should be seen. If there isn’t any, there might be something goes wrong while the page is posting form values(index.php) or reading them(save.php).

      Did you make sure you are using the files in this link? https://github.com/kublaios/html2canvas-basic

      If you are using these files, I’m sure it’s something about the PHP .ini file configuration. Search Google for PHP POST issues.

      Kind regards.

  • Hello Kubilay!
    Seems like a really good script. I’d love to use it, but I seem to be having some troubles.
    My web server supports PHP, but every time I try using this script (installed like explained) the PHP code on the next page pops up, and doesn’t seem to work.
    If you’d like an image of what I’m trying to explain,
    http://i.imgur.com/zwPs1xz.png
    Hope you can help. Thanks!

    • Hi Nick,

      Thanks for the explanation with image.

      Don’t get me wrong, but did you make sure that you have included < ?php and ?> opening-closing tags? Seems like the php code is not being executed.

      So either you have problem with your server’s PHP configuration, or you have a problem with your PHP file. Try to use your code somewhere else (like free web hostings) and see if you have any trouble with them.

      Hope this helps,
      Kubilay

  • Hi Kubilay,

    It could not capture the HTML’s radio and checkbox element that are selected.

    Button and Textbox works. Any solution to solve this?

    Thanks for your effort.

    Regards,
    Dimanche

    • Hi Dimanche,

      If the script captures a checkbox as unchecked even though it was checked, that seems to be a real problem.

      I don’t have a straight solution but I think you may want to make sure that your checkbox status is being posted, if not then there’s something that removes the checkbox status; if it is being posted, then I guess it’s something about html2canvas’ abilities. You should try to contact with the developer, too.

      Hope you can work it out.
      Kind regards,
      Kubilay

  • Hey Kubilay,

    Fantastic code!
    I would like to know if this is possible without the server -side saving? If I removed the PHP, could I just simply open the saved image in a new tab once the ‘Save’ button is pressed?

    Also, I have not tested your code, but could the radio and checkbox problem be removed if jQuery UI was used instead of the basic HTML form elements?

    Thanks,
    Jade

    • Hi Jade,

      Thank you. I think you can use the same PHP script with $_GET values instead of $_POST while you send the img_val field’s value with query. jQuery’s ajax() function may be able to do that.

      I haven’t tried anything with radio and checkboxes but perhaps your suggestion would work. If I can try it in some proper time, I’ll update the original post in case it works.

      Thanks again, cheers.

      • Hey Kubilay,

        Thanks for your response.

        I have heard from many people that the HTML2Canvas library lacks saving the selected radio buttons and checkbox’s. There must be a solution to this, and I think that maybe using jQuery UI might be the solution since it creates its own HTML form elements instead of re-styling the default HTML form elements.

        I can try and give it a shot and post back here, but I’m flat out with work. Would be fantastic if someone could find a solution to this as it is an ongoing problem.

        Thanks,
        Jade

        • Hi again Jade,

          You are right. Though it might depends on the page JS events cycle, as long as the jQuery UI events happen before the html2canvas, I think UI might prove your opinion right.

          So it’s definitely worth trying. Let’s hope that people who need solution about this read your comment and tries, even give us a feedback.

          Cheers,
          Kubilay

  • eerriicc46

    HI Dimanche… i had the same results untill i try it on others browsers than internet explorer (10 for me).

  • Maddy

    I am getting javascript error here “Error: TypeError: doc is undefined” Please suggest.

  • Hafiz

    there is any way that i can convert div into image if div is hidden? currently i am working on wordpress
    please help

    • Hi Hafiz,

      At the very beginning of canvas onrendered event (after “onrendered: function (canvas) {” line), set your div’s css attributes to make it visible.

      You can use jQuery’s css() function.

      Kind regards,
      Kubilay

  • Towfiq

    Is it possible to increase the quality of the image? right now its pretty bad… :/

  • This is how you do checkbox and radio:

    ———-
    function capture() {
    //HANDLE ALL CHECKBOXES & RADIOS
    var ThisImg = ”;
    var myStringArray = ["checkbox","radio"];
    for (var i = 0; i < myStringArray.length; i++) {
    $('form input:'+myStringArray[i]).each(function() {
    var ThisDiv = 'Div_'+this.name;
    var input = $(this)
    .wrap( "” )
    .parent()
    if( this.checked ) {
    ThisImg = “/includes/”+myStringArray[i]+”_checked.jpg”
    } else {
    ThisImg = “/includes/”+myStringArray[i]+”_unchecked.jpg”
    }
    $(‘#’+ThisDiv).empty();
    $(‘#’+ThisDiv).prepend(”)
    });
    }
    //RENDER SCREENSHOT
    $(‘#target’).html2canvas({
    onrendered: function (canvas){
    $(‘#img_val’).val(canvas.toDataURL(“image/png”));
    document.getElementById(“orderform”).submit();
    }
    });
    }
    ———-

    All you need to make this work is the above code are image files of checked and unchecked: checkbox and radio.

    The way I did it was to simply take screenshots of the existing checkbox and radio both checked and unchecked and use those. That way the size is perfect and they look like the original.

    Cheers! :D

    • Hi Stu,

      I haven’t tried myself but it seems like a proper way. I have shared your comment’s link in the original post so that people can notice easier.

      Thank you for your contribution.

      Kind regards,
      Kubilay

  • Thanks a lot for the amazing and time saving tutorial. This is the missing bit to the originators of the html2canvas code. They did an amazing job but their documentation lacks exactly what you have in this post. I think it would be brilliant if you could contact them and request them to let you write this article on their site. I believe this article would add 200% more value to what they have. Just saying. gain, thank you.

    • Hi SpencerB,

      Thank you for your advice, I will consider it.

      I agree with you about the documentation as I mentioned in the tutorial that how it was tough for me to implement it basically. I’m glad that it helped you, you are welcome.

      Regards,
      Kubilay

  • Yannick

    Thanks for this tutorial it really did saved me a lot of work.

    If the image in the webpage are hosted on a different server they won’t be added to the screenshot … Any solution for that.

    for ex:

    (works)
    but not

  • Ramki

    Hi, thanks for tutorial, i tried your tutorial. i got one problem. i have div with css background image. after i convert that div into img i got only the text. i didt get css background image. what will be the problem????

    • I suggest you to check two things:
      1- Your internet browser. It might be outdated or not supporting some canvas abilities.
      2- Image path. If it’s not on your server and you are using its absolute URL, it might be a problem. You can see previous comments that remote content can cause problems sometimes. So save the image to your server and give a relative path like url(../images/background.png).

      Hope this helps. Regards.

  • Nice article dude. I was searching for this. Thanks

  • gbec78

    hey Kubilay great work! any chance you can tell me though how to convert the code on the save.php page to save this to my SQL Database instead of my server? I want an actual newimage.png file that i can save on my sql server, then create a link to that image and save the url in a table…

    Example:

    convert this: “which you previously provided”

    //Show the image
    echo ”;

    //Get the base-64 string from data
    $filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], “,”)+1);

    //Decode the string
    $unencodedData=base64_decode($filteredData);

    //Save the image
    file_put_contents(‘img.png’, $unencodedData);

    to this:

    $newname = “$NEWIMAGE.jpg”;
    move_uploaded_file($_FILES['fileField1']['tmp_name'], “../mywebsite/images/$newname”);
    $logo1 = “http://www.myurl.com/mywebsite/images/$newname”;
    }

    • Hi,

      When you save the image with the code I shared, (Line: file_put_contents(‘img.png’, $unencodedData);), there’s an actual image on the server named “img.png”.

      All you have to do is move it to wherever you want with move_uploaded_file() function like this:
      move_uploaded_file(‘img.png’, ‘../mywebsite/images/$newname’);

      Then save the new path (‘../mywebsite/images/$newname’) in your database so you can access it later.

      Hope this helps,
      Kind regards.

  • Juan Manuel Ortega

    Please help me,
    I want load the image into the same index.php, but in other div.
    How can I do?

    • Hi,

      Then you don’t need step 5, the PHP file.

      Also, don’t submit the form as it was told in the step 4.

      In the div you want to show the image, create an image with an id like “targetImg”.

      Then in step 4, replace the code:
      $(‘#img_val’).val(canvas.toDataURL(“image/png”));
      To this:
      $(‘#targetImg’).attr(‘src’, canvas.toDataURL(“image/png”));

      That should work for you.

      You see, normally we load the image data to a hidden field named img_val so we can post it with the form and read it on the server side (5th step). Thus we can actually create a physical image file. But if you don’t need that, things are easier for you.

      I’m not sure if $(‘#targetImg’).attr() will work, but you need to set some property of $(‘#targetImg’), if it’s not attr(‘src’), it could be $(‘#targetImg’).val(canvas.toDataURL(“image/png”)). If still not working, search about showing an image with javascript using base64 value.

      Regards.

  • I wish I had save.php pages in ASP?
    You could send her?
    Sorry for the english but translate by google.

    Thank you.

  • abiraman

    hi,
    i include div’s from jquery.i used this function yhat nothing captured.and also the image.
    please help me

  • abiraman

    it captured text but not captured image
    please help me
    thank u

    • Hi,

      I think this problem occurs when the image is loaded from an external URL. Please check this situation.

      Regards,
      Kubilay

  • abiraman

    hi, thanks for your solution.i load my image from external url. what i do for this.my images are in my server.

    please help me…

    thank u….

  • abiraman

    i convert my images in to my localhost.it takes screen shot.but not get full image.its only get(513×490)

    please help me

  • abiraman

    hi, i tried to capture screen short in firefox(version 22.0).its work perfectly.but chrome(version Version 31.0.1650.63)not works.

    please reply me quickly…

    • Hi,

      Like I said at the end of the tutorial, I have used previous version of html2canvas. You should try out the latest release and official examples if the code above doesn’t work.

      Regards,
      Kubilay

  • hey bro thanks a lot everything works perfectly :)

    how can i do this tweak?
    im working on my wordpress site in which i want a the content of a post to be converted to image..when i capture a post it saves it to the server has “img.png”… but when i click capture again on a different post it replaces the previous image “img.png”. can i save these images with different names? like post names maybe?

    • Hi,

      Of course you can. For example, you can use the ticks concept which means the seconds count from the first date.

      In step 5, replace this line:
      file_put_contents(‘img.png’, $unencodedData);
      With this:
      file_put_contents(‘img_’.strototime().’.png’, $unencodedData);

      strtotime() function returns a different number per second. So your image names will be different each time.

      If you want a custom file name like article names, you have more work to do. You can post the desired file name with the HTML form (E.g. place an input in the form created on step 3). In server side, what you need to change is step 5.

      Hope this helps,
      Regards.

      • you are awesome bro.. thanks a lot :)

      • Hi bro.. i used strtotime() functions is works good. but its kinda akward to look into the image each time to see what data it has, can you please tell how to rename it with article name?
        i tried this

        <input type="hidden" name="” id=”img_val” value=”" />

        but im sorry im not good with code.. your help is greatly appreciated. thank you

        • Hi,

          If you put a “hidden” field, you cannot set its value. Try to put a text field like:
          input type=”text” name=”fileName” value=”" />

          Then you will see a text input. Whatever you type in here will be posted to server side in $_POST["fileName"] variable.

          So in step 5, while setting the file name, use this value like:
          file_put_contents($_POST["fileName"].’.png’, $unencodedData);

          Hope this helps,
          Regards.

  • kajol

    kajol

    im running this on word-press.. captured files save in theme root directory.

    can i save them directly to
    /public_html/wp-content/uploads ?

  • Shweta

    Hi ,

    Thanks a lot for this one Kubilay.

    I am trying to download the captured image on client side instead.
    But my code works starting from second click onwards. It does not work for the first click.

    Below is my code :

    $(document).ready(function () {
    $(“.export”).click(function () {
    var image_url=null;
    var element = $(this);
    $(this).closest(‘div’).html2canvas({
    onrendered: function (canvas) {
    image_url = canvas.toDataURL(“image/png”);
    //var element = $(this);
    if(image_url){
    element.attr({
    ‘download’: “image.png”,
    ‘href’: image_url,
    ‘target’: ‘_blank’
    });
    }
    }
    });
    });
    });

    Inputs appreciated.

    • Hi Shweta,

      I couldn’t see any problem either, it seems we are missing a point or there’s another thing affects the element.

      However, I think you can try a little trick like triggering the second click manually. How about something like this:

      if(image_url){
      element.attr({
      ‘download’: “image.png”,
      ‘href’: image_url,
      ‘target’: ‘_blank’
      });

      // new line
      element.click();
      //

      }

      Hope this helps,
      Regards.

  • Domus Maximus

    I have used GrabzIt’s JavaScript API to capture a divs content in the past. Here is a article (http://grabz.it/api/javascript/capturediv.aspx) on how to do it.

  • Amayas

    Great !! Thx for this tuto…
    How to do this in Java/JS/html2canvas ?

Leave a reply


− 5 = four