简体   繁体   English

使用 JavaScript 下载图像

[英]Download image with JavaScript

Right now I have a canvas and I want to save it as PNG.现在我有一个canvas ,我想将它保存为 PNG。 I can do it with all those fancy complicated file system API, but I don't really like them.我可以用所有那些花哨的复杂文件系统 API 来做到这一点,但我真的不喜欢它们。

I know if there is a link with download attribute on it:我知道是否有带有download属性的链接:

<a href="img.png" download="output.png">Download</a>

it will download the file if the user clicks on it.如果用户点击它,它将下载文件。 Therefore I came up with this:因此我想出了这个:

$("<a>")
    .attr("href", "img.png")
    .attr("download", "output.png")
    .appendTo("body")
    .click()
    .remove();

Demo: http://jsfiddle.net/DerekL/Wx7wn/演示: http : //jsfiddle.net/DerekL/Wx7wn/

However, it doesn't seem to work.但是,它似乎不起作用。 Does it have to be trigger by an user action?它是否必须由用户操作触发? Or else why didn't it work?否则为什么它不起作用?

The problem is that jQuery doesn't trigger the native click event for <a> elements so that navigation doesn't happen (the normal behavior of an <a> ), so you need to do that manually.问题是 jQuery 不会触发<a>元素的本机click事件,因此导航不会发生( <a>的正常行为),因此您需要手动执行此操作。 For almost all other scenarios, the native DOM event is triggered (at least attempted to - it's in a try/catch).对于几乎所有其他场景,本机 DOM 事件都会被触发(至少尝试过 - 它在 try/catch 中)。

To trigger it manually, try:要手动触发它,请尝试:

var a = $("<a>")
    .attr("href", "http://i.stack.imgur.com/L8rHf.png")
    .attr("download", "img.png")
    .appendTo("body");

a[0].click();

a.remove();

DEMO: http://jsfiddle.net/HTggQ/演示: http : //jsfiddle.net/HTggQ/

Relevant line in current jQuery source: https://github.com/jquery/jquery/blob/1.11.1/src/event.js#L332当前 jQuery 源中的相关行: https : //github.com/jquery/jquery/blob/1.11.1/src/event.js#L332

if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
        jQuery.acceptData( elem ) ) {

As @Ian explained , the problem is that jQuery's click() is not the same as the native one.正如@Ian解释的那样,问题在于 jQuery 的click()与本机的click()不同。

Therefore, consider using vanilla-js instead of jQuery:因此,请考虑使用 vanilla-js 而不是 jQuery:

var a = document.createElement('a');
a.href = "img.png";
a.download = "output.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

Demo演示

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

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