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>
7
  • I told you in your other question that Google doesn't allow this: stackoverflow.com/revisions/14580361/1
    – Marcelo
    Commented Jan 30, 2013 at 8:57
  • how about read the div, then draw the content by yourself? Commented Feb 1, 2013 at 4:32
  • 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'
    Commented Feb 1, 2013 at 5:37
  • where you get those errors ? in my sample ? Why question is even related to googleapis.com ?
    – zb'
    Commented Feb 1, 2013 at 6:17
  • the cause of that issue that http://html2canvas.appspot.com/ does not exists
    – zb'
    Commented Feb 1, 2013 at 6:20

10 Answers 10

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>
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. Commented Feb 9, 2013 at 15:36
  • is this html2canvas element compatable in IE8 and below versions? Commented Oct 24, 2013 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. Commented Jan 7, 2014 at 0: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);
  }
});
1
  • 1
    How can we save it as Popup save option?
    – Moxet Jan
    Commented Jan 4, 2015 at 6:56
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);
    }
});
0
9

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.

3
  • your code works very well on my purpose. But is it possible to save the specific div id from function var? For example, I have 10 divs with '#div1' to '#div10'. Can I just 'onClick="myfunc('#div1')" and it generate the image of that div?
    – Wilf
    Commented Oct 24, 2023 at 14:24
  • @Wilf Try it and see if it works.
    – Dexter
    Commented Oct 25, 2023 at 21:58
  • 1
    it works for me, tnx :)
    – Hamid
    Commented May 31 at 19:34
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();
});
2
  • Why is useCORS needed?
    – Dror Bar
    Commented Nov 10, 2020 at 9: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
    Commented Nov 12, 2020 at 7: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>
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.

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!

0
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/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);
1
  • convert 64 image in href tag Commented Mar 23, 2023 at 10:27
-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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.