简体   繁体   中英

html2canvas error if I download printscreen second time

I implemented html2canvas for downloading printscreen by clicking on button. If I click first time everything is ok but after second time I got a following error:

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

at

body.id = 'capture';

so body is null I don't understand why. Maybe some browser restrictions?

Demo https://jsfiddle.net/janzitniak/bn4Lrcy3/9/

I found a workaround for that (using index for added canvas), getting right code:

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)

demo is available at https://jsfiddle.net/janzitniak/bn4Lrcy3/46/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM