如何不使用html2canvas将我的html div转换为canvas?

时间:2018-10-03 06:27:27

标签: javascript html2canvas

我需要将html div转换为canvas,并且我现在正在使用html2canvas 但它仅捕获窗口的可见部分。我的意思是说,它并不能捕获具有水平滚动的整个潜水。

因此,有什么方法可以通过水平滚动或在html2canvas中的任何建议来捕获整个div。

这是我使用的代码

var element = document.getElementsByClassName('ppm_portlet_data');

    html2canvas(element[0], { width: element[0].offsetWidth, height: element[0].offsetHeight }).then(function (canvas) {
            console.log(canvas.toDataURL());
            Canvas2Image.saveAsPNG(canvas);
            console.log(canvas.width, canvas.height);
         });

1 个答案:

答案 0 :(得分:2)

您必须使用scrollWidthscrollHeight并设置overflow: visible;才能获得不可见的内容。

Working Example

const div = document.querySelector('#content');
div.innerText = div.innerText.split(' ').join(''); // just for overflowing content

div.addEventListener('click', event => {
    html2canvas(div, { width: div.scrollWidth, height: div.scrollHeight }).then(canvas => {
        document.body.appendChild(canvas);
        console.log(canvas.width, canvas.height); // outputs greater width than browser width
    });
});
#content {
    overflow: visible; /* make overflow visible to capture */
    word-wrap: nowrap;
}
<body>
    <div id='content'>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus.
    </div>

  <script type="text/javascript" src='https://html2canvas.hertzen.com/dist/html2canvas.min.js'></script>
</body>