不,似乎没有任何事件让您知道具有该
download属性的锚点是否实际上已成功下载资源。
但是,您面临的限制似乎仅与这种情况有关:
<a>具有
download属性的锚元素。
浏览器可以处理更长的dataURI(我认为在大多数浏览器中,限制与字符串长度的限制相同)。例如,它可以将其加载到
<img>element上,更重要的是,它可以处理dataURI字符串。
这很重要,因为它允许您将dataURI转换为Blob,然后
object URL从该Blob 创建一个。
objectURL的URI很小,在带有
download属性的锚点中不会遇到此长度限制。
因此,根据您的情况,最好的
canvas.toBlob方法是直接使用该方法mdn上提供了polyfill,并将
objectURL的URI作为
href锚点的传递。
var img = new Image();img.crossOrigin = "anonymous";img.onload = function(){ var ctx = document.createElement('canvas').getContext('2d'); ctx.canvas.width = this.width*10; ctx.canvas.height = this.height*10; ctx.drawImage(this,0,0,ctx.canvas.width, ctx.canvas.height); // convert our canvas to a png blob // (for type use the second parameter, third is for quality if type is image/jpeg or image/webp) ctx.canvas.toBlob(function(blob){ myAnchor.href = URL.createObjectURL(blob); }); // since we are dealing with use files, we absolutely need to revoke the ObjectURL as soon as possible var revokeURL = function(){ // but we have to wait that the browser actually prepared the file to download requestAnimationframe(function(){ // we've waited one frame, it's seems to be enough URL.revokeObjectURL(this.href); this.href=null; }); this.removeEventListener('click', revokeURL); }; myAnchor.addEventListener('click', revokeURL); };img.src = 'http://lorempixel.com/200/200/';<a id="myAnchor" download="anAwesomeImage.png">download</a>(由于
downloadSE摘录中的某些UA阻止了该属性)
但是请注意,即使的字符串表示形式(URI)
objectURL很短,它实际上也会占用浏览器内存中文件的大小,因此,直到您硬刷新页面(清除缓存)或关闭创建位置的标签为止此对象的网址。因此,您绝对需要致电
URL.revokeObjectURL()以清除此空间。
但是,由于没有事件可知道下载是否真正成功,因此您将受困于该
onclick事件,该事件将 在 文件下载发生 之前
触发。从我的测试中,等待一个帧
requestAnimationframe就足够了,但是我可能错了。
对于那些使用画布以外的其他来源来获取其dataURI的消息,SO中已经有很多关于将dataURI转换为Blob的文章,您可以检查上面提供的mdn
polyfill,他们正在这样做太。



