Screenshot of hidden div using html2canvas

Viewed 39800

How to take screenshots of a hidden div? The code given below is not working for hidden div.

HTML

<div id="mydiv" style="display:none;" >  
 <p>Text</p>
</div>

<div id="canvas" style="display:none;">
<p>Canvas:</p>
</div>

 <div id="image">

  </div>

SCRIPT

<script>
  var elem = $('#printDiv');
        html2canvas(elem, {
            onrendered: function (canvas) {
                var data = canvas.toDataURL('image/png');
                var image = new Image();
                image.src = data;
                document.getElementById('image').appendChild(image);
            }
        });

</script>

It works when we set the style of the div "mydiv" as 'display:block'.

9 Answers
html2canvas(mydiv, {
    onclone: function (clonedDoc) {
        clonedDoc.getElementById('mydiv').style.display = 'block';
    }
}).then((canvas)=>{
//your onrendered function code here
})

The following code worked for me. I am using Angular with jsPdf and html2canvas libraries

    html2canvas(document.getElementById("pdfTable"), {
  onclone: function (clonedDoc) {

     // I made the div hidden and here I am changing it to visible
    clonedDoc.getElementById('pdfTable').style.visibility = 'visible';
  }
}).then(canvas => {
  // The following code is to create a pdf file for the taken screenshot
  var pdf = new jsPDF('l', 'pt', [canvas.width, canvas.height]);
  var imgData = canvas.toDataURL("PNG", 1.0);
  pdf.addImage(imgData, 0, 0, (canvas.width), (canvas.height));
  pdf.save('converteddoc.pdf');
});

This is working:

<div style="width:0;height:0;overflow: hidden"> <div> content to screenshot </div> </div>

you can create a canvas function and then you can show and hide based on it. I'm also using jsPDF to convert images to pdf. like this

   function generateCanvas() {
        html2canvas(document.querySelector("#yourid"), {
            scrollX: 0,
            scrollY: -window.scrollY
        }).then(canvas => {
            //var imgData = canvas.toDataURL("image/jpeg", 2.0);
        var imgData = canvas.toDataURL({
                format: 'jpeg',
                quality: 1.0
            });
    
        $("#canvas_container").attr("src", imgData);
            var pdf = new jsPDF();
            pdf.addImage(imgData, 'JPEG', 10, 10, 180, 150);  // 180x150 mm @ (10,10)mm
            pdf.save("download.pdf");
        });
    }
    
    $("#download_pdf").on("click", function (e) {
        e.preventDefault();
        $("#yourid").show();
        generateCanvas();
        $("#yourid").hide();
    })
Related