简体   繁体   中英

How to download canvas image(base64) in javascript

I am using html2canvas. Chrome downloads the image but other browser don't download the image.

This is the code:

html2canvas($("body")[0], {
        onrendered: function(canvas) {
      var img = canvas.toDataURL("image/png");
      var link = document.createElement('a');
      link.download = "test.png";
      link.href = img;
      link.click();
        }
    });

How can I get the image to download on other browsers?

download attribute is not wide compatible.

http://caniuse.com/#feat=download

However, it works in Firefox, Chrome, Opera and Android, if doesn't work for you it's probably because the user doesn't make a click event (you are attempting to download on rendered event), so Chrome have a security bug.

If user doesn't make click in nowhere, no clicks will be triggered due security reasons. Obvious.

It works for me if I add the link into the page before trigger click as below,

document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);

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