Last active
April 4, 2017 16:35
-
-
Save SaneMethod/ee52a37e9f2dc276bd73 to your computer and use it in GitHub Desktop.
Canvas toBlob Shim, adapated with thanks from https://code.google.com/u/105701149099589407503/.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Canvas toBlob shim, adapted with thanks from https://code.google.com/u/105701149099589407503/, | |
* from this chrome bug thread: https://code.google.com/p/chromium/issues/detail?id=67587 | |
*/ | |
(function(){ | |
/** | |
* Convert a base64 image dataURL from a canvas element, to a blob. | |
* @param {function} callback | |
* @param {string} type | |
* @param {number} quality | |
* @param {base64=} dataURL The dataURL to use, rather than fetch from the canvas. | |
*/ | |
function dataURLToBlob(callback, type, quality, dataURL){ | |
dataURL = dataURL || this.toDataURL(type, quality); | |
var bin = atob(dataURL.split(',')[1]), | |
len = bin.length, | |
len32 = len >> 2, | |
a8 = new Uint8Array(len), | |
a32 = new Uint32Array(a8.buffer, 0, len32), | |
tailLength = len & 3; | |
for(var i=0, j=0; i < len32; i++) | |
{ | |
a32[i] = bin.charCodeAt(j++) | | |
bin.charCodeAt(j++) << 8 | | |
bin.charCodeAt(j++) << 16 | | |
bin.charCodeAt(j++) << 24; | |
} | |
while(tailLength--) | |
{ | |
a8[j] = bin.charCodeAt(j++); | |
} | |
callback(new Blob([a8], {'type': type || 'image/png'})); | |
} | |
if(HTMLCanvasElement && Object.defineProperty && !HTMLCanvasElement.prototype.toBlob) | |
{ | |
Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', | |
{ | |
value:dataURLToBlob | |
}); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, thank you!