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

4
我可以使用以下代码在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'));

});
2个回答

11

谢谢Dibsy Jr,你可以建议其他解决方法吗? - Bikshu s
2
根据您需要支持的浏览器版本,您可以使用以下内容:https://github.com/blueimp/JavaScript-Canvas-to-Blob该内容充当浏览器中toBlob方法的polyfill。 - DibsyJr
如果这篇文章对您有所帮助,请选择它作为最佳答案并点赞。 - DibsyJr
1
现在看来,实际上 Safari 中有一些支持(参见引用的 URL)。 - thesquaregroot
感谢 @thesquaregroot,我已经添加了一个编辑说明它是何时添加的。 - DibsyJr

3

MDN上发布了一个基于toDataURL的低性能填充物,与之相关的是HTMLCanvasElement/toBlob

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

      });
    }
  });
}

1
这在Edge中不起作用。它将错误从“不是函数”更改为“期望函数”。但仍然无法工作。我还没有找到一个在Edge中有效的toBlob polyfill。 - M H
有趣的是,最近我进行的一项测试在Edge上运行良好,因此自四月以来可能发生了一些变化。 - thesquaregroot

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