使用 JavaScript 下载图像 [英] Download image with JavaScript

查看:16
本文介绍了使用 JavaScript 下载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有一个 canvas,我想将它保存为 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.

我知道是否有带有 download 属性的链接:

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 不会触发 元素的原生 click 事件这样导航就不会发生( 的正常行为),因此您需要手动执行此操作.对于几乎所有其他场景,原生 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).

要手动触发,请尝试:

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆