如何在 html 和 javascript 中截屏?

How to take a screenshot in html with javascript?

我是 html 和 javascript 的新手。我正在尝试截取 html 页面的屏幕截图并将其保存为 jpgpng 文件。

这是我的 html 图片

我想通过拖放 divs 按下图像右上角的图像保存按钮截取右侧(灰色)的屏幕截图。

如何使用 html 和 javascript 进行屏幕截图? 我看到了一些 html2canvas 但这不是我想要的。我觉得..

有人对此有想法吗?

谢谢,

p.s。如果你想要我的 html 的代码,我可以 EDIT

您只能使用 Canvas 捕获图像或视频帧作为屏幕截图。但是,如果您想捕获网页上的特定元素,请尝试使用这样的库:html2canvas

代码如下:

注意:在drawImage()函数中仔细调整尺寸

$(".drag").draggable();
$(".drag").droppable();
var takeScreenShot = function() {
    html2canvas(document.getElementById("container"), {
        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/jpg');   //function blocks CORS
            link.download = 'screenshot.jpg';
            link.click();
        }
    });
}
#container{
    width:400px;
    height:200px;
}
#rightcontainer{
    width:300px;
    height:200px;
    background:gray;
    color:#fff;
    margin-left:110px;
    padding:10px;
}
#leftmenu{
    color:#fff;
    background-color:green;
    width:100px;
    height:200px;
    position:fixed;
    left:0;
    padding:10px;
}

button{
    display:block;
    height:20px;
    margin-top:10px;
    margin-bottom:10px;
}
.drag{
  width:40px;
  height:20px;
  background-color:blue;
  z-index:100000;
  margin-top:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
  
  
<button onclick="takeScreenShot()">Snapshot</button>
<div id="container">
    <div id="leftmenu">
      Left Side
      <div class="drag">
      </div>
      <div class="drag">
      </div>
      <div class="drag">
      </div>
      Drag----------->
            &
      Click Snapshot
    </div>
    <div id="rightcontainer">
        Right Side
    </div>
</div>