将 html 字符串呈现为 canvas 而不显示 html 本身

Rendering html string to canvas without showing the html itself

我想将 html 字符串转换为图像,类似于此处的操作: html2canvas creates a canvas with a width and height of zero?

但是我不想在页面上显示结果图像以外的任何内容。因此,我不能按照那里的建议简单地将 html 字符串添加到 DOM 中。我认为我正在努力实现的目标是可能的,因为 html2canvas test console 就是这样做的。

我尝试了以下产生空结果的方法:

var doc = document.implementation.createHTMLDocument();
doc.open();
doc.write("<html><header></header><body><div>test</div></body></html>");
doc.close();

html2canvas(doc.body, {
    onrendered:function(newCanvas) {
        document.body.appendChild(newCanvas);
    }    
});
<script src="https://github.com/niklasvh/html2canvas/blob/master/dist/html2canvas.js"></script>

任何人都可以建议这样做的方法吗?

我明白了。这是 the link which headed me to the right direction. It is also worth checking the source code of this page 说明了这个想法。

我们设置

style="overflow:hidden"

容器的属性,并使用

将我们要渲染的内容移动到视口之外
style="position:absolute;top:0px;left:3000px;"

希望对某人有所帮助。