45

I'm trying to capture a div into an image using html2canvas

I have read some similar question here like

How to upload a screenshot using html2canvas?

create screenshot of web page using html2canvas (unable to initialize properly)


I have tried the code

canvasRecord = $('#div').html2canvas(); 
dataURL = canvasRecord.toDataURL("image/png");

and the canvasRecord will be undefined after .html2canvas() called


and also this

$('#div').html2canvas({
      onrendered: function (canvas) {
           var img = canvas.toDataURL()
           window.open(img);
      } 
});

browser gives some (48 to be exact) similar errors like:

GET http://html2canvas.appspot.com/?url=https%3A%2F%2Fmts1.googleapis.com%2Fvt%…%26z%3D12%26s%3DGalileo%26style%3Dapi%257Csmartmaps&callback=html2canvas_1 404 (Not Found) 

BTW, I'm using v0.34 and I have added the reference file html2canvas.min.js and jquery.plugin.html2canvas.js

How can I convert the div into canvas in order to capture the image.

EDIT on 26/Mar/2013

I found Joel's example works.

But unfortunately when Google map embedded in my app, there will be errors.

<html>
<head>
<style type="text/css">
div#testdiv
{
    height:200px;
    width:200px;
    background:#222;
}
div#map_canvas
{
    height: 500px;
    width: 800px;
    position: absolute !important;
    left: 500px;
    top: 0;
}
</style>
 <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>
<script type="text/javascript" src="html2canvas.min.js"></script>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script language="javascript">
$(window).load(function(){
     var mapOptions = {
        backgroundColor: '#fff',
        center: new google.maps.LatLng(1.355, 103.815),
        overviewMapControl: true,
        overviewMapControlOptions: { opened: false },
        mapTypeControl: true,
        mapTypeControlOptions: { position: google.maps.ControlPosition.TOP_LEFT, style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
        panControlOptions: { position: google.maps.ControlPosition.RIGHT_CENTER },
        zoomControlOptions: { position: google.maps.ControlPosition.RIGHT_CENTER },
        streetViewControlOptions: { position: google.maps.ControlPosition.RIGHT_CENTER },
        disableDoubleClickZoom: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        minZoom: 1,
        zoom: 12
    };
    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

    $('#load').click(function(){

            html2canvas($('#testdiv'), {
                onrendered: function (canvas) {
                    var img = canvas.toDataURL("image/png")
                    window.open(img);
                }
            });

    });
});
</script>
</head>
<body>
<div id="testdiv">
</div>
<div id="map_canvas"></div>
<input type="button" value="Save" id="load"/>
</body>
</html>
Timeless
  • 7,338
  • 9
  • 60
  • 94
  • I told you in your other question that **Google doesn't allow this**: http://stackoverflow.com/revisions/14580361/1 – Marcelo Jan 30 '13 at 08:57
  • how about read the div, then draw the content by yourself? – Michael Law Feb 01 '13 at 04:32
  • http://jsbin.com/atijon/3/edit this works for you ?(i not found built 0.34, so it is 0.40) I will explain if it is answer you looking for. – zb' Feb 01 '13 at 05:37
  • where you get those errors ? in my sample ? Why question is even related to googleapis.com ? – zb' Feb 01 '13 at 06:17
  • the cause of that issue that `http://html2canvas.appspot.com/` does not exists – zb' Feb 01 '13 at 06:20
  • @Timeless in **[my sample](http://jsbin.com/atijon/3/edit)** ? – zb' Feb 01 '13 at 06:21
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/23751/discussion-between-eicto-and-timeless) – zb' Feb 01 '13 at 06:22

10 Answers10

24

I ran into the same type of error you described, but mine was due to the dom not being completely ready to go. I tested with both jQuery pulling the div and also getElementById just to make sure there wasn't something strange with the jQuery selector. Below is an example that works in Chrome:

<html>
<head>
<style type="text/css">
div {
    height: 50px;
    width: 50px;
    background-color: #2C7CC3;
}
</style>
<script type="text/javascript" src="html2canvas.js"></script>
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script language="javascript">
$(document).ready(function() {
//var testdiv = document.getElementById("testdiv");
    html2canvas($("#testdiv"), {
        onrendered: function(canvas) {
            // canvas is the final rendered <canvas> element
            var myImage = canvas.toDataURL("image/png");
            window.open(myImage);
        }
    });
});
</script>
</head>
<body>
<div id="testdiv">
</div>
</body>
</html>
Joel Schlundt
  • 292
  • 1
  • 3
  • 3
    I tried another test and added an image as an element of the div and also changing the background of the div to an image. Basically, it won't work if you are trying to access the html or image file from the file system in chrome. The security restrictions will cause it to fail. `Unable to get image data from canvas because the canvas has been tainted by cross-origin data.` If you host it in a server, it will work. – Joel Schlundt Feb 09 '13 at 15:36
  • is this html2canvas element compatable in IE8 and below versions? – Hariprasath Oct 24 '13 at 11:21
  • 1
    @Hariprasath: it was until v0.3.4 but then they dropped support. I tried using v0.3.4 but this throws errors for me at least. – hugo der hungrige Jan 07 '14 at 00:30
22

If you just want to have screenshot of a div, you can do it like this

html2canvas($('#div'), {
  onrendered: function(canvas) {
    var img = canvas.toDataURL()
    window.open(img);
  }
});
J.J. Kim
  • 1,845
  • 1
  • 16
  • 21
11

you can try this code to capture a div When the div is very wide or offset relative to the screen

var div = $("#div")[0];
var rect = div.getBoundingClientRect();

var canvas = document.createElement("canvas");
canvas.width = rect.width;
canvas.height = rect.height;

var ctx = canvas.getContext("2d");
ctx.translate(-rect.left,-rect.top);

html2canvas(div, {
    canvas:canvas,
    height:rect.height,
    width:rect.width,
    onrendered: function(canvas) {
        var image = canvas.toDataURL("image/png");
        var pHtml = "<img src="+image+" />";
        $("#parent").append(pHtml);
    }
});
wang ye
  • 111
  • 1
  • 2
5

10 2022

This question is quite old, but if anyone looking for a clear solution to implement then here it is. This is using Pure JS with html2canvas and FileSaver

I have tested and it works fine.

Capture everything inside a div.

Step 1

Include the scripts in your footer. jQuery is not needed, These two are fine. If you already have these two in your file, watch out for the correct version. I know it's a little thing, but it is important.

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js"></script>

Step 2

Basic div. The style attribute is optional. I am using it here to make it look presentable.

<div id="savethegirl" style="background-color:coral;color:white;padding:10px;width:200px;">
    I am a Pretty girl 
</div>

<button onclick="myfunc()">Save the girl</button>

It should look like this

enter image description here

Step 3

Include this script

function myfunc(){
    // if you are using a different 'id' in the div, make sure you replace it here.
    var element = document.getElementById("savethegirl");
    html2canvas(element).then(function(canvas) {
        canvas.toBlob(function(blob) {
            window.saveAs(blob, "Heres the Girl.png");
        });
    });
};

Step 4

Click the button and it should save the file.

Resources

CDN from: https://cdnjs.com/ This is from Carlos Delgado's article (https://ourcodeworld.com/articles/read/415/how-to-create-a-screenshot-of-your-website-with-javascript-using-html2canvas). I simplified it

If this answer is useful.
Hit that up arrow It will help others to find it.

Dexter
  • 7,911
  • 4
  • 41
  • 40
3

You can get the screenshot of a division and save it easily just using the below snippet. Here I'm used the entire body, you can choose the specific image/div elements just by putting the id/class names.

 html2canvas(document.getElementsByClassName("image-div")[0], {
  useCORS: true,
}).then(function (canvas) {
  var imageURL = canvas.toDataURL("image/png");
  let a = document.createElement("a");
  a.href = imageURL;
  a.download = imageURL;
  a.click();
});
ExOrIntro
  • 221
  • 3
  • 7
  • Why is useCORS needed? – Dror Bar Nov 10 '20 at 09:23
  • 2
    If your corresponding div containing any images from other domains, it will not show that images if you haven't enabled the useCors. In my case I have some images from other blob storage domains, So useCors is enabled. – ExOrIntro Nov 12 '20 at 07:17
2

I don't know if the answer will be late, but I have used this form.

JS:

function getPDF()  {
       html2canvas(document.getElementById("toPDF"),{
        onrendered:function(canvas){
 
        var img=canvas.toDataURL("image/png");
        var doc = new jsPDF('l', 'cm'); 
        doc.addImage(img,'PNG',2,2); 
        doc.save('reporte.pdf'); 
       }
    }); 
}

HTML:

<div id="toPDF"> 
    #your content...
</div>

<button  id="getPDF" type="button" class="btn btn-info" onclick="getPDF()">
    Download PDF
</button>
Dropdread
  • 21
  • 2
1

It can be easily done using html2canvas, try out the following,

try adding the div inside a html modal and call the model id using a jquery function. In the function you can specify the size (height, width) of the image to be displayed. Using modal is an easy way to capture a html div into an image in a button onclick.

for example have a look at the code sample,

`

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">


            <div class="modal-body">
                <p>Some text in the modal.</p>

`

paste the div, which you want to be displayed, inside the model. Hope it will help.

Thomas Martin
  • 666
  • 2
  • 6
  • 26
1

window.open didn't work for me... just a blank page rendered... but I was able to make the png appear on the page by replacing the src attribute of a pre-existing img element created as the target.

$("#btn_screenshot").click(function(){
     element_to_png("container", "testhtmltocanvasimg");
});


function element_to_png(srcElementID, targetIMGid){
    console.log("element_to_png called for element id " + srcElementID);
    html2canvas($("#"+srcElementID)[0]).then( function (canvas) {
        var myImage = canvas.toDataURL("image/png");
        $("#"+targetIMGid).attr("src", myImage);
  console.log("html2canvas completed.  png rendered to " + targetIMGid);
    });
}
<div id="testhtmltocanvasdiv" class="mt-3">
   <img src="" id="testhtmltocanvasimg">
</div>

I can then right-click on the rendered png and "save as". May be just as easy to use the "snipping tool" to capture the element, but html2canvas is an certainly an interesting bit of code!

user3232196
  • 169
  • 1
  • 5
0
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/canvas2image@1.0.5/canvas2image.min.js"></script>        
        <script type="text/javascript" `enter code here`src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>

<a  id="btnExport" value="Export"  >Export</a>
<div id="map"></div>  
//your  map key  & script

setTimeout (function(){
                html2canvas($("#map"), {
                                useCORS: true,
                                onrendered: function (canvas) {
                                        $("#btnExport").attr("href", canvas.toDataURL("image/png"));
                                        $("#btnExport").attr("download", "Dashboard.png")
                                }
                        });
        },200);
-2

You should try this (test, works at least in Firefox):

html2canvas(document.body,{
   onrendered:function(canvas){
      document.body.appendChild(canvas);
   }
});

Im running these lines of code to get the full browser screen (only the visible screen, not the hole site):

var w=window, d=document, e=d.documentElement, g=d.getElementsByTagName('body')[0];
var y=w.innerHeight||e.clientHeight||g.clientHeight;

html2canvas(document.body,{
   height:y,
   onrendered:function(canvas){
      var img = canvas.toDataURL();
   }
});

More explanations & options here: http://html2canvas.hertzen.com/#/documentation.html

Marcus
  • 1,222
  • 2
  • 13
  • 22