用JavaScript下载图片 [英] Download image with JavaScript
问题描述
现在我有一个画布
,我想把它保存为PNG。我可以用所有这些复杂的文件系统API来完成,但是我并不喜欢它们。
Right now I have a canvas
and I want to save it as PNG. I can do it with all those fancy complicated file system API, but I don't really like them.
我知道是否有一个下载
属性:
I know if there is a link with download
attribute on it:
<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();
演示: 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?
推荐答案
问题是jQuery不会触发本机单击
事件,以便导航不会发生(< a>
元素的的正常行为<一个>
),所以你需要手动这样做。对于几乎所有其他情况,本地DOM事件被触发(至少尝试 - 它在一个try / catch中)。
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. For almost all other scenarios, the native DOM event is triggered (at least attempted to - it's in a try/catch).
要手动触发它,请尝试: p>
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();
演示: http://jsfiddle.net/HTggQ/
当前jQuery的相关行来源:https://github.com/jquery/jquery/blob/1.11.1/src/event.js#L332如果((!special._default || special._default.apply(eventPath.pop(),data)=($)
Relevant line in current jQuery source: 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 ) ) {
这篇关于用JavaScript下载图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!