Canvas toBlob在safari中不被识别为函数

Canvas toBlob is not recognized as a function in safari

本文关键字:识别 函数 toBlob safari Canvas      更新时间:2023-09-26

我可以在Chrome下载图像&Firefox使用下面的代码,但在Safari中,它会抛出这个错误:

TypeError: 'undefined'不是一个函数(求值'canvas.toBlob(blobCallback('wallpaperdeae'))')

$("#save").click(function(){
   function blobCallback(iconName) {
        return function (b) {
            var a = document.getElementById('download');
            a.download = iconName + ".jpg";
            a.href = window.URL.createObjectURL(b);
        }
    }
    canvas.toBlob(blobCallback('wallpaperdeae'));
});

我认为Safari不支持toBlob方法:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob Browser_compatibility

根据这一点,它只能在Chrome 50+和Firefox(19+为基本支持,25+为图像质量参数)中使用,在IE 10及以上版本中有一些基本支持。

所以不支持Safari。

编辑:根据引用的URL支持在2017年9月19日发布的Safari 11中添加了toBlob方法

MDN上有一个"基于toDataURL的低性能polyfill "

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