首页 > 解决方案 > MSEdge 浏览器中 canvas.toBlob() 的兼容性

问题描述

我正在使用canvas.toBlob()回调方法将图像文件转换为 blob。但我看到这toBlob与微软边缘浏览器不兼容。

我尝试检测浏览器并根据我使用的浏览器toBlob()。对于 Edge,我们有canvas.msToBlob(),对于其他浏览器,我们有canvas.toBlob(). 我们有什么通用的方法来创建一个 blob 吗?

 let isEdgeBrowser = 
 msie\s|trident\/|edge\//i.test(window.navigator.userAgent);
    if (isEdgeBrowser) {
      let blob = canvas.msToBlob();
    }

   if (!isEdgeBrowser) {
      canvas.toBlob((blob) => {
        this.fileUploadedSize = blob.size;
      });
    }

标签: javascripthtmlhtml5-canvasmicrosoft-edge

解决方案


根据这篇文章,我们可以看到 HTMLCanvasElement.toBlob() 方法不支持 Edge 浏览器,如果要在 Edge 浏览器中使用该方法,请尝试添加以下 polyfill:

if (!HTMLCanvasElement.prototype.toBlob) {
  Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
    value: function (callback, type, quality) {
      var dataURL = this.toDataURL(type, quality).split(',')[1];
      setTimeout(function() {

        var binStr = atob( dataURL ),
            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'} ) );

      });
    }
  });
}

推荐阅读