Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas to blob on Edge

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

like image 652
uvytautas Avatar asked Nov 24 '17 14:11

uvytautas


People also ask

How do you convert a canvas to a blob?

The HTMLCanvasElement. toBlob() method creates a Blob object representing the image contained in the canvas. This file may be cached on the disk or stored in memory at the discretion of the user agent. The desired file format and image quality may be specified.

Can I use canvas to blob?

If you're wondering whether you can draw image blobs to another canvas context, the answer is -- in Firefox and Chrome -- yes, absolutely! You can do this with the createImageBitmap() API, which is also landing in Chrome 50.

What is HTMLCanvasElement?

The HTMLCanvasElement interface provides properties and methods for manipulating the layout and presentation of <canvas> elements. The HTMLCanvasElement interface also inherits the properties and methods of the HTMLElement interface.


1 Answers

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

like image 143
isAlex Avatar answered Oct 02 '22 15:10

isAlex