将隐藏的DIV保存为画布图像

问题描述 投票:0回答:1

我使用以下代码将可见图像保存为。

html2canvas(document.querySelector('.specific'), {
        onrendered: function(canvas) {
        theCanvas = canvas;
        Canvas2Image.saveAsPNG(canvas); 
    }
});

有什么方法可以保存隐藏的内容

javascript html html5-canvas html2canvas
1个回答
1
投票

有一些解决方案,例如显示属性切换,或隐藏元素内部渲染。

解决方案1

快速切换可见性属性

const el = document.querySelector('.specific');
el.style.display = "block"; // or any other property, like opacity, visibility...
html2canvas(el, {...}).then((canvas) => {
   el.style.display = "none";
};

解决方案2

在隐形包装内包裹你的div(并使其可见)

<div style="position: absolute; opacity: 0; pointer-events:none;">
    <div class="specific"></div>
</div>

要么

<div style="overflow: hidden; height: 0;">
    <div class="specific"></div>
</div>

解决方案3

使用html2canvas onclone回调函数你可以修改传递给渲染器的对象(我认为这是最好的解决方案)

html2canvas(document.querySelector('.specific'), {
    onclone: function(doc){
        doc.style.display = 'block';
        // or doc.style.opacity = '1', doc.style.visibility = 'visible' ...
    },
    onrendered: function(canvas) {
        theCanvas = canvas;
        Canvas2Image.saveAsPNG(canvas); 
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.