Canvas to blob on Edge

uvytautas picture uvytautas · Nov 24, 2017 · Viewed 7.3k times · Source

Getting exception on Microsoft Edge browser when trying to convert Html canvas element to blob. Everything works great on normal browsers. Exception:

SCRIPT438: Object doesn't support property or method 'toBlob'

Html snippet:

<canvas id="cnv" width="640px" height="520px" style="display: none"></canvas>

Javascript:

var files[];
var canvas = document.getElementById('cnv');
canvas.toBlob(function (blob) {            
        files.push(blob);
         }
    }, 'image/jpeg', 1);

I get this exception right when I call toBlob method. Are there any ways to teach Edge blob converting? I am using :

Microsoft Edge 41.16299.15.0

Answer

isAlex picture isAlex · Nov 25, 2017

This small polyfill taken from here must help see jsfiddle

if (!HTMLCanvasElement.prototype.toBlob) {
   Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
     value: function (callback, type, quality) {
       var canvas = this;
       setTimeout(function() {
         var binStr = atob( canvas.toDataURL(type, quality).split(',')[1] ),
         len = binStr.length,
         arr = new Uint8Array(len);

         for (var i = 0; i < len; i++ ) {
            arr[i] = binStr.charCodeAt(i);
         }

         callback( new Blob( [arr], {type: type || 'image/png'} ) );
       });
     }
  });
}

This could help as well github.com/blueimp/JavaScript-Canvas-to-Blob