简体   繁体   中英

capture div into image using html2canvas

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>

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>

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);
  }
});

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);
    }
});

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

在此处输入图像描述

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.

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>

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.

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!

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();
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM