html2canvas returns 当body高度超过30000像素时图片无效

html2canvas returns invalid image when the body height is more than 30000 pixels

当我需要捕获放置在长度超过 30000 像素的 html 主体上的控件时,html2canvas 库表现异常。我的控件很小 (100 x 100) - 但是当主体很长时脚本不起作用。


这里有两个小提琴,一个在工作,一个不工作不同的体型

$(document).ready(function() {
  $('#test').on('click', function() {
    html2canvas(document.getElementById('container'), {
      onrendered: function(canvas) {
        document.body.appendChild(canvas);
      },
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>

<body style="height:40000px">

 <button id="test">test</button>

 <div id='container'>
   <img style='width:200px; height:200px;' src="www.example.com/example.jpg">
 </div> 
</body>

 

在上面的例子中,库 returns 一张图片 - 但数据无效。如果我将 body 高度更改为 20000 像素,一切正常

终于根据this Whosebug answer

找到了为什么会这样

html2canvas库创建了一个canvas它的宽高是文档正文的宽高。如果文档宽度或高度超过浏览器允许的最大宽度和高度,则无法为该文档正文创建 canvas,这就是我得到无效图像的原因。

为了解决这个问题,我克隆了要传输到图像的元素并设置到文档的顶部 ('position: absolute; top: 0') 并从中获取图像。获取图像后,我删除了该克隆元素。记得这样做我们需要设置 "html2canvas" 库选项的宽度和高度 属性。

我的情况是我的元素最大高度为 1000px,我设置为 3000、3000 因此它可以覆盖位于顶部的整个元素。

注意:不要设置不可见或隐藏克隆的元素。

html2canvas($parentNode, { 
    width: 3000,
    height:3000,
    onrendered: function(canvas) {
        console.log(canvas.toDataURL());
        $parentNode.remove(); //removing cloned element
    }
});
$('#test').click(function () {
    // Create clone of element.
    var clone = $('#element').clone(); 

    // Append clone to body.
    $('body').append(clone); 

    html2canvas($('#element'), {
        onrendered: function (canvas) {
            console.log(canvas.toDataURL("image/png")); 

           // Remove clone element.
          clone.remove();
        }
    });
});

对我在 html2canvas 之前将样式 overflow-y:hidden 添加到 body 标记并在 之后将其恢复为 overflow-y:scroll 有效。

$("#doss").click(function(){
    $('body').css('overflow-y','hidden');
    html2canvas(document.querySelector("body")).then(canvas => {
       document.body.appendChild(canvas)
    });
    $('body').css('overflow-y','scroll');
});`