第一种:Image + canvas
const getBase64Image = src => {return new Promise(resolve => {const img = new Image()img.crossOrigin = ''img.src = srcimg.onload = function () {const canvas = document.createElement('canvas')canvas.width = img.widthcanvas.height = img.heightconst ctx = canvas.getContext('2d')ctx?.drawImage(img, 0, 0, img.width, img.height)const ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()const dataURL = canvas.toDataURL('image/' + ext)resolve(dataURL)}})}
第二种:xhr + FileReader
const getBase64Image = src => {return new Promise(resolve => {let xhr = new XMLHttpRequest()xhr.open('get', src, true)xhr.responseType = 'blob'xhr.onload = function () {if (this.status == 200) {let blob = this.responselet oFileReader = new FileReader()oFileReader.onloadend = function (e) {const base64 = e.target.resultresolve(base64)}oFileReader.readAsDataURL(blob)}}xhr.send()})}