I'm trying to find a clean and consistent approach for downloading the contents of a canvas as an image file.
For Chrome or Firefox, I can do the following
// 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 + '">');
Since the above doesn't work in IE, I'm trying to build a Blob with the 'window.navigator.msSaveOrOpenBlob' function.
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");
In the example above, do I really have to convert a canvas to base64, base64 to ArrayBuffer, and finally convert from base64 to blob? (Firefox has a 'canvas.toBlob' function, but again that's not available in IE). Also, this only works in IE10, not IE9.
Does anyone have any suggestions for a solution that will work in Chrome, Safari, Firefox, IE9, and IE10?
Yes you have to do all the extra footwork.
toBlob
support in Chrome and FF is very recent, even though its been in the spec for several years. Recent enough that it wasn't even on the radar when MS made IE9 and 10.
Unfortunately MS has no intent of changing IE9 or IE10 canvas implementations, which means they will exist as they are for all eternity, with bugs and missing pieces. (IE10 canvas has several bugs that IE9 does not, that are fixed again in IE11. Like this gem. It's a real shamble.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With