class Demo {

/**
* 根据图片 URL 直接获取到 DataURL
**/
convertImgToDataURLviaCanvas(url, callback, outputFormat) {
const img = new Image()
img.crossOrigin = 'Anonymous' // canvas 不能处理跨域图片,如果要处理,除了服务端要开启跨域外,执行canvas操作前也要开启跨域
img.onload = function () {
let canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
let dataURL = ''
canvas.height = this.height
canvas.width = this.width
ctx.drawImage(this, 0, 0)
dataURL = canvas.toDataURL(outputFormat)
callback(dataURL)
canvas = null
}
img.src = url
}

/**
* 根据图片 URL 直接获取到 Blob
**/
convertImgToBlobviaCanvas(url, callback) {
const img = new Image()
img.crossOrigin = 'Anonymous' // canvas 不能处理跨域图片,如果要处理,除了服务端要开启跨域外,执行canvas操作前也要开启跨域
img.onload = function () {
let canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
let dataURL = ''
canvas.height = this.height
canvas.width = this.width
ctx.drawImage(this, 0, 0)
canvas.toBlob(callback)
canvas = null
}
img.src = url
}

/**
* 把文件转成 dataURL 通过 fileReader
**/
convertFileToDataURLviaFileReader(url, callback) {
const xhr = new XMLHttpRequest()
xhr.responseType = 'blob'
xhr.onload = function () {
const reader = new FileReader()
reader.onloadend = function () {
callback(reader.result)
}
reader.readAsDataURL(xhr.response)
}
xhr.open('GET', url)
xhr.send()
}

/**
* 把 dataURL 转成 blob
**/
dataURLToBlob(dataurl) {
console.log('datarul', dataurl)
let arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], { type: mime })
}
}