簡體   English   中英

如果我第二次下載打印屏幕,則出現 html2canvas 錯誤

[英]html2canvas error if I download printscreen second time

我通過單擊按鈕實現了 html2canvas 來下載打印屏幕。 如果我第一次點擊一切正常,但第二次點擊后出現以下錯誤:

Uncaught TypeError: Cannot set property 'id' of null
    at HTMLButtonElement.capture

body.id = 'capture';

所以 body 是 null 我不明白為什么。 也許一些瀏覽器限制?

演示https://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/ 獲得

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM