在 h5 端转 base64 下载图片,在红米手机浏览器中下载,但是没有资源输出,所以增加了安卓判断,把 base64 转了 blob 进行下载
base64ToBlob(code) {
let parts = code.split(';base64,')
let contentType = parts[0].split(':')[1]
let raw = window.atob(parts[1])
let rawLength = raw.length
let uInt8Array = new Uint8Array(rawLength)
for (let i = 0
uInt8Array[i] = raw.charCodeAt(i)
}
return new Blob([uInt8Array], {
type: contentType
})
},
// 下载图片
loadCode(imgsrc, name) {
let image = new Image()
// 解决跨域 Canvas 污染问题
image.setAttribute('crossOrigin', 'anonymous')
// console.log('imgsrc--', image)
image.src = imgsrc
const that = this
image.onload = function () {
let canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
let context = canvas.getContext('2d')
context.drawImage(image, 0, 0, image.width, image.height)
let url = canvas.toDataURL('image/png')
let a = document.createElement('a')
let event = new MouseEvent('click')
a.download = name || 'image-' + new Date().getTime()
// 区别 iso 和 android 下载方式
if (that.curSystem === 'android') {
let blob = that.base64ToBlob(url)
a.href = URL.createObjectURL(blob)
} else {
a.href = url
}
a.dispatchEvent(event)
}
},