Search code examples
javascripthtmlcssasp.nethtml2canvas

Html2canvas print screenshot


I have this piece of code in .aspx that should print the selected part of my web function.

           <div id="test" class="body-content animated fadeIn">
                <a href="javascript:getScreenshot()"> Get Sreenshot </a>
                <script>
                    function getScreenshot() {
                        html2canvas(divprint, {
                            onrendered: function(canvas) {
                                var canvasImg = canvas.toDataURL("image/jpg");
                                $('#test').html('<img src="'+canvasImg+'" alt="">');
                            }
                        });
                        var printContent = document.getElementById("test");
                        var printWindow = window.open("", "","left=50,top=50");
                        printWindow.document.write(printContent.innerHTML);
                        printWindow.document.write("<script src=\'http://code.jquery.com/jquery-1.10.1.min.js\'><\/script>");
                        printWindow.document.write("<script>$(window).load(function(){ print(); close(); });<\/script>");
                        printWindow.document.close();
                    }
                </script>
                ...

But clicking the the text "Get Sreenshot" nothing happens. Do you understand why? When I remove

                       html2canvas(divprint, {
                            onrendered: function(canvas) {
                                var canvasImg = canvas.toDataURL("image/jpg");
                                $('#test').html('<img src="'+canvasImg+'" alt="">');
                            }
                        });

it works more or less well


Solution

  • The latest version of html2canvas uses promises rather than the 'onrendered` callback.
    eg.

    html2canvas(document.querySelector('#my-thing')).then(function(canvas) {
      // do something with canvas here.
      console.log(canvas);
    });