javascript - 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;
});
}
解决方案
根据这篇文章,我们可以看到 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'} ) );
});
}
});
}
推荐阅读
- ansible - 首次尝试多次播放剧本文件时,Ansible 跳过剧本
- selenium - Selenium 如何点击一个标签使用引导下拉类
- oracle - 将变量的内容假脱机到文件中
- r - 根据条件重新排列字符串中的单词
- python - Python递归函数返回None而不是值
- php - Laravel 7 身份验证尝试返回 false
- html - 防止内容溢出到下一页
- css - 在 css (otf) 中指定自定义字体 - 提供多个 otf 文件时如何指定粗体/斜体/等?
- ionic-framework - 离子电容相机,文件plugin_not_install
- aem - 如何确保 AEM 6.4 代码与 AEM 6.5 兼容