简体   繁体   English

如何在JavaScript中下载canvas图像(base64)

[英]How to download canvas image(base64) in javascript

I am using html2canvas. 我正在使用html2canvas。 Chrome downloads the image but other browser don't download the image. Chrome会下载图片,但其他浏览器不会下载图片。

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. download属性不广泛兼容。

http://caniuse.com/#feat=download 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. 但是,它适用于Firefox,Chrome,Opera和Android,如果对您不起作用,可能是因为用户没有进行点击事件(您正尝试在渲染的事件上下载),因此Chrome存在安全漏洞。

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, 如果我click如下所示在触发click之前将link添加到页面中,那么它对我有用,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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