在Edge浏览器中将Canvas转换为Blob

15

在尝试将HTML画布元素转换为blob时,在Microsoft Edge浏览器上出现异常。在普通浏览器上一切都很好运行。

异常:

SCRIPT438:对象不支持属性或方法'toBlob'

HTML代码片段:

<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);

当我调用toBlob方法时,我会得到这个异常。有没有什么方法可以教Edge如何转换blob? 我正在使用:

Microsoft Edge 41.16299.15.0

2个回答

28

这个小的 polyfill 取自于这里,必须帮助查看 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'} ) );
       });
     }
  });
}

这也可能会有帮助github.com/blueimp/JavaScript-Canvas-to-Blob


0
如果您正在使用 webpackES6,那么请通过npm安装此软件包
npm install blueimp-canvas-to-blob

然后像这样导入包

import "blueimp-canvas-to-blob/js/canvas-to-blob";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接