【问题标题】:html2canvas render only the visible part of div elementhtml2canvas 只渲染 div 元素的可见部分
【发布时间】:2021-04-15 17:30:02
【问题描述】:

我正在使用 html2canvas 截取页面中可滚动的 div 元素。 但是,它只呈现可见的内容而不是整个 div。

这是一个小例子:https://codepen.io/johnhckuo/pen/abpGrmr

我做了一些搜索,看到其他人建议在 html2canvas 参数中设置scrollY: -window.scrollY。 但这对我不起作用。

有人在这个问题上有经验吗? 谢谢!

【问题讨论】:

    标签: javascript css html2canvas


    【解决方案1】:

    尝试向#photo 添加一个不受 CSS 约束的子元素 - 像这样:

    <div id="photo">
    <div id = "photo-inner">
            <button onclick="takeshot()">
            Take Screenshot
        </button>
        <h1>Test</h1>
        Hello everyone! This is a
        trial page for taking a
        screenshot.
        <br><br>
        This is a dummy button!
        <button> Dummy</button>
        <br><br>
        Click the button below to
        take a screenshot of the div.
        <br><br>
        <button onclick="takeshot()">
            Take Screenshot
        </button>
    </div>
    </div>
    

    然后,让子元素成为html2canvas的目标:

    let div = document.getElementById('photo-inner');
    

    (这在你的 Codepen 中有效,我无法 fork,因为我没有注册。)

    【讨论】:

    • 它工作!太感谢了。是不是因为之前html2canvas受#photo的css属性影响,所以只显示部分div?
    • html2canvas 对一些 CSS 规则有点严格。通过添加一个没有 CSS 的子 div,您可以让它获得完整的内容。
    猜你喜欢
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    相关资源
    最近更新 更多