我有一个任务,需要在我的网页上加载 URL
(e.g www.yahoo.com)
并截取屏幕截图。我使用 html2canvas 进行屏幕截图并将其附加到页面正文中。
URL 指定的页面已成功加载到 div 元素内的 iframe 中。但当我尝试截取该屏幕截图时,iframe 区域变为空白。
以下是
previewURL
和screenshot
的代码。
//to preview the URL content
function previewUrl(url,target){
//use timeout coz mousehover fires several times
clearTimeout(window.ht);
window.ht = setTimeout(function(){
var div = document.getElementById(target);
div.innerHTML = '<iframe style="width:100%;height:100%;" frameborder="0" src="' + url + '" />';
},20);
}
function pic() {
html2canvas(document.body, {
onrendered: function(canvas) {
document.body.appendChild(canvas);
}
});
};
HTML 部分位于此处:
<body>
<input type="button" class="clear-button" onclick="pic();" value="Take Screenshot" >
<a href="http://www.yahoo.com" onmouseover="previewUrl(this.href,'div1')">Hover to load</a>
<div id="div1"></div>
</body>
屏幕截图看起来像这样:
我被困住了,不明白为什么会发生这种情况。我想要类似 this 的东西,它可以加载 URL,然后 onclick 可以给我截图。
这里的问题是您没有正确指向
iframe
中您想要截图的部分,而是直接指向文档正文。
你可以试试这个:
var body = $(iframe).contents().find('body')[0];
html2canvas(body, {
onrendered: function( canvas ) {
$("#content").empty().append(canvas);
},
希望这有帮助!
好像不可能:
该脚本不会呈现插件内容,例如 Flash 或 Java 小程序。它也不渲染 iframe 内容。
http://html2canvas.hertzen.com/documentation.html#limitations
这段代码对我有用:
setTimeout(() => {
html2canvas($('#'+idd2).contents().find('body')[0], {
allowTaint : true,
logging: true,
profile: true,
useCORS: true
}).then(function(canvas) {
document.getElementById('screen').appendChild(canvas);
}); }, 3000);
您的渲染页面和 iframe URL 存在跨域冲突。 顺便说一下,我的问题是这样解决的: 您可以通过
iframeElement.contentWindow.document.body
获取 iframe 内容,然后创建该内容的图像,并在创建主图像时将其替换为 iframe 元素