我正在尝试使用HTML2Canvas来渲染div的内容。这是代码:
var htmlSource = $('#potenzial-page')[0];
$('#btn').on("click", function() {
html2canvas(htmlSource).then(function(canvas) {
var img = canvas.toDataURL();
window.open(img);
});
});
我正在使用v5 beta 3。
此代码运行时,它仅呈现屏幕上可见的内容。 #potenzial-page
div基本上是整个页面,减去页眉和页脚。通过滚动可以看到此div中的所有内容(有一些隐藏元素,但我不希望隐藏元素在图像中可见。)
我找不到什么是错的,或者为什么它不能保存整个div。我还应该注意到,图像看起来和div一样高,但只是部分可见。
举一个我的意思的例子,这是一个比较:
左边是HTML2Canvas应该如何呈现div。右边显示了它在运行上面的代码时如何呈现。正确的图像是我的浏览器屏幕中可见的图像。
我确实尝试添加height
选项,但它没有任何区别。
UPDATE
如果我滚动到页面的最顶部然后运行脚本它将呈现整个div应该。
如何渲染div而不必滚动到顶部?
对我有用的解决方案是将以下内容添加到我的CSS中:
.html2canvas-container { width: 3000px !important; height: 3000px !important; }
它可以防止html2canvas将渲染限制在可视区域(这似乎是默认区域)。
您是否在SO中看到了这个解决方案:“Html2canvas converting overflowed content to image”提出了一种解决方案,将溢出设置为可见,然后渲染然后溢出隐藏。
我用window.scrollTo()
in我的情况,它对我有用。
下面是一个示例代码
$('#btn').on("click", function() {
window.scrollTo(0,0);
html2canvas(htmlSource).then(function(canvas) {
var img = canvas.toDataURL();
window.open(img);
});
window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);
});
window.scrollTo(0,0);
添加这个适合我。
我刚刚做了这样的事情,它对我有用:
html2canvas(document.querySelector("#capture2image"), {
allowTaint: true,
useCORS: true,
logging: false,
height: window.outerHeight + window.innerHeight,
windowHeight: window.outerHeight + window.innerHeight,