html2canvas:截取div工作的屏幕截图

时间:2017-11-01 15:14:16

标签: javascript jquery html canvas html2canvas

我想使用javascript截取DOM中元素的屏幕截图,并自动将其保存在我的本地计算机上,而无需点击按钮。我见过很多建议,但没有一个真正按照我想要的方式工作。这是我读过的一些例子。 example1example 2

<!DOCTYPE html>
<html>
<body>
<script src="jquery-3.2.1.min.js"></script>
<p>This is some text.</p>

<div style="color:#0000FF" id="myContainer" >
<h3>This is a heading in a div element</h3>
<p>This is some text in a div element.</p>
</div>

 <p>This is some text.</p>
 <script type="text/javascript">
 try { 
    debugger;
    $.getScript("html2canvas.js", function() {  

                        var takeScreenShot = function() {

                        html2canvas($("#myContainer"), {

                       onrendered: function (canvas) {

                            var tempcanvas=document.createElement("canvas");

                            tempcanvas.width=350;
                            tempcanvas.height=350;
                            var context=tempcanvas.getContext("2d");

                        context.drawImage(canvas,112,0,288,200,0,0,350,350);
                             var link=document.createElement("a");
                              link.href=tempcanvas.toDataURL("image/png")
                              link.download = "myImage.png";
                              link.click();

                           }
                        }); 
                     }  }); 

    }
   catch (err) {
         alert(err.message);
 }

 </script>
</body>
</html>

问题是我没有收到任何错误,我没有截图。

1 个答案:

答案 0 :(得分:0)

您正在定义函数takeScreenShot,但从未实际调用它。您需要使用takeScreenShot();

调用该函数

或更完整:

try { 
debugger;
$.getScript("html2canvas.js", function() {  

                    var takeScreenShot = function() {

                    html2canvas($("#myContainer"), {

                   onrendered: function (canvas) {

                        var tempcanvas=document.createElement("canvas");

                        tempcanvas.width=350;
                        tempcanvas.height=350;
                        var context=tempcanvas.getContext("2d");

                    context.drawImage(canvas,112,0,288,200,0,0,350,350);
                         var link=document.createElement("a");
                          link.href=tempcanvas.toDataURL("image/png")
                          link.download = "myImage.png";
                          link.click();

                       }
                    }); 
                 }  
               takeScreenShot();
          }); 

}
catch (err) {
     alert(err.message);
}