开满天机
信息: IE10 +完全不支持以下方法。其他人已经完成了工作并实现了跨浏览器解决方案。 这就是其中之一。首先,将生成的数据URL添加到标签的href属性中<a>。但是,在某些浏览器中,仅此一项就不会触发下载。相反,它将在新页面中打开链接的图像。Base64映像的“下载”对话框:<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUg...." class="image" />根据以上示例,将数据URL的MIME类型转换为此:<a href="data:application/octet-stream;base64,iVBORw0KGgoAAAANSUhEUg....">Download</a>通过告诉浏览器数据是application/octet-stream,它将要求您将其保存在硬盘上。指定文件名:正如Adi在下面的评论中所说,没有使用这种方法定义文件名的标准方法。但是,有两种方法可能在某些浏览器中有效。A)downloadGoogle Crome引入的属性<a download="image.png" href="...">B)在数据URL中定义HTTP标头headers=Content-Disposition: attachment; filename=image.png<a href="data:application/octet-stream;headers=Content-Disposition%3A%20attachment%3B%20filename=image.png;base64,iVBORw0KGgoAAAA">这至少在某些较旧的Opera版本中有效。 这里是一些讨论。对主要浏览器的Bug /功能跟踪系统的研究表明,定义文件名是社区的一个很大愿望。也许我们会在不久的将来看到跨浏览器兼容的解决方案!;)节省RAM和CPU资源:如果您不想膨胀访问者的浏览器的RAM,还可以动态生成数据URL:<a id="dl" download="Canvas.png">Download Canvas</a>function dlCanvas() { var dt = canvas.toDataURL('image/png'); this.href = dt;};dl.addEventListener('click', dlCanvas, false);这样,您的画布仍可能被浏览器显示为图像文件。如果要增加打开下载对话框的可能性,则应扩展上述功能,以便它进行替换,如上所示:function dlCanvas() { var dt = canvas.toDataURL('image/png'); this.href = dt.replace(/^data:image\/[^;]/, 'data:application/octet-stream');};dl.addEventListener('click', dlCanvas, false);最后,添加HTTP标头以确保大多数浏览器为您提供有效的文件名!;)完整示例:var canvas = document.getElementById("cnv");var ctx = canvas.getContext("2d");/* FILL CANVAS WITH IMAGE DATA */function r(ctx, x, y, w, h, c) { ctx.beginPath(); ctx.rect(x, y, w, h); ctx.strokeStyle = c; ctx.stroke();}r(ctx, 0, 0, 32, 32, "black");r(ctx, 4, 4, 16, 16, "red");r(ctx, 8, 8, 16, 16, "green");r(ctx, 12, 12, 16, 16, "blue");/* REGISTER DOWNLOAD HANDLER *//* Only convert the canvas to Data URL when the user clicks. This saves RAM and CPU ressources in case this feature is not required. */function dlCanvas() { var dt = canvas.toDataURL('image/png'); /* Change MIME type to trick the browser to downlaod the file instead of displaying it */ dt = dt.replace(/^data:image\/[^;]*/, 'data:application/octet-stream'); /* In addition to <a>'s "download" attribute, you can define HTTP-style headers */ dt = dt.replace(/^data:application\/octet-stream/, 'data:application/octet-stream;headers=Content-Disposition%3A%20attachment%3B%20filename=Canvas.png'); this.href = dt;};document.getElementById("dl").addEventListener('click', dlCanvas, false);<canvas id="cnv" width="32" height="32"></canvas><a id="dl" download="Canvas.png" href="#">Download Canvas</a>