我正在尝试找到一种干净且一致的方法来将 Canvas 的内容下载为图像文件。
对于 Chrome 或 Firefox,我可以执行以下操作
// Convert the canvas to a base64 string
var image = canvas.toDataURL();
image = image.replace(/^data:[a-z]*;/, 'data:application/octet-stream;');
// use the base64 string as the 'href' attribute
var download = $('<a download="' + filename + '" target="_blank" href="' + image + '">');
由于以上在 IE 中不起作用,我正在尝试使用“window.navigator.msSaveOrOpenBlob”函数构建一个 Blob。
var image = canvas.toDataURL();
image = image.replace(/^data:[a-z]*;,/, '');
// Convert from base64 to an ArrayBuffer
var byteString = atob(image);
var buffer = new ArrayBuffer(byteString.length);
var intArray = new Uint8Array(buffer);
for (var i = 0; i < byteString.length; i++) {
intArray[i] = byteString.charCodeAt(i);
}
// Use the native blob constructor
blob = new Blob([buffer], {type: "image/png"});
// Download this blob
window.navigator.msSaveOrOpenBlob(blob, "test.png");
在上面的示例中,我真的必须将 canvas 转换为 base64,将 base64 转换为 ArrayBuffer,最后从 base64 转换为 blob 吗? (Firefox 具有“canvas.toBlob”功能,但在 IE 中同样不可用)。此外,这仅适用于 IE10,不适用于 IE9。
有人对适用于 Chrome、Safari、Firefox、IE9 和 IE10 的解决方案有任何建议吗?
最佳答案
是的,您必须完成所有额外的步法。
toBlob
在 Chrome 和 FF 中的支持是非常最近的,尽管它已经在规范中存在了好几年。最近足够了,当 MS 制作 IE9 和 10 时,它甚至没有出现在雷达上。
不幸的是,MS 无意更改 IE9 或 IE10 Canvas 实现,这意味着它们将永远存在,但会存在错误和缺失部分。 (IE10 Canvas 有几个 IE9 没有的错误,在 IE11 中再次修复。Like this gem.这真是一团糟。)
关于javascript - HTML canvas 到 IE9、10 中的可下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19736726/