使用html2canvas能否截取URL的屏幕截图?

4

以下代码可以截取当前页面的屏幕截图。在html2canvas中是否可能截取URL的屏幕截图呢?我的意思是我有一个URL,它是

mydomain.com/home
mydomain.com/home?id=2
mydomain.com/home/2

现在,如何截取屏幕并在另一页上显示截图图片?

window.takeScreenShot = function() {
    html2canvas(document.getElementById("target"), {
        onrendered: function (canvas) {
            document.body.appendChild(canvas);
        },
        width:320,
        height:220
    });
}
#target{
    width:300px;
    height:200px;
    background:blue;
    color:#fff;
    padding:10px;
}
button{
    display:block;
    height:20px;
    margin-top:10px;
    margin-bottom:10px;
}
<div id="target">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque quis eleifend elit. Donec lectus sem, scelerisque sit amet facilisis quis, gravida a lacus. Nunc at lorem egestas, gravida lorem quis, pulvinar ante. Quisque id tempus libero. Mauris hendrerit nunc risus, ac laoreet lectus gravida et. Nam euismod magna ac enim posuere sagittis. Fusce at egestas enim, eu hendrerit enim.
</div>

<button onclick="takeScreenShot()">to image</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://html2canvas.hertzen.com/build/html2canvas.js"></script>


分享关闭此问题的原因对我来说是很好的。 - Naren Verma
1个回答

2

您可以使用iframe来加载其他文档,在其加载事件中调用html2canvas与iframe的contentDocument.documentElement,就可以完成操作。

[当然,这仅适用于同源文档]

var iframe = document.createElement('iframe');
iframe.src = YOUR_SAME_DOMAIN_URL_HERE
iframe.onload = function(e) {   
  // note: this assumes html2canvas v5+
   html2canvas(iframe.contentDocument.documentElement).then(function(canvas){
     document.body.removeChild(iframe);
     doSomethingWithTheCanvas(canvas);
    });
}
// just to hide the iframe
iframe.style.cssText ='position: absolute; opacity:0; z-index: -9999';
document.body.appendChild(iframe);

作为一个 JSFiddle,因为 StackSnippet 的空源 iframe 禁用了对内部 iframe 的访问……


我无法理解这个fiddle的输出。 - Naren Verma
输出中的内容是html2canvas函数的画布结果。你不明白什么? - Kaiido
它没有显示截图,只显示文本。 - Naren Verma
我该如何使用你上面的代码?我只是在这行输入了URL iframe.src = YOUR_SAME_DOMAIN_URL_HERE 但什么也没有发生。 - Naren Verma
让我们在聊天中继续这个讨论 - Naren Verma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接