我通过点击按钮实现了用于下载打印屏幕的html2canvas。如果我第一次点击一切正常,但第二次之后我得到了以下错误:
Uncaught TypeError: Cannot set property 'id' of null
at HTMLButtonElement.capture
在
body.id = 'capture';
所以身体是空的,我不明白为什么。也许有一些浏览器限制?
Demohttps://jsfiddle.net/janzitniak/bn4Lrcy3/9/
我找到了一个解决方法(使用索引添加画布(,得到了正确的代码:
var index = -1;
var body = document.querySelector('#example1');
var capture = () => {
body.id = 'capture';
html2canvas(document.querySelector("#capture")).then(canvas => {
document.body.appendChild(canvas);
}).then(() => {
var canvas = document.querySelectorAll('canvas')[index];
canvas.style.display = 'none';
var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
var a = document.createElement("a");
a.setAttribute('download', 'excelo.online-output.png');
a.setAttribute('href', image);
a.click();
});
index++;
};
var btn = document.getElementById('btnPrintScreen');
btn.addEventListener('click', capture)
演示可在https://jsfiddle.net/janzitniak/bn4Lrcy3/46/