Skip to content

Instantly share code, notes, and snippets.

@SaneMethod
Last active April 4, 2017 16:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SaneMethod/ee52a37e9f2dc276bd73 to your computer and use it in GitHub Desktop.
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/.
/**
* 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
});
}
})();
@PatrickWatzlawik
Copy link

Nice, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment