思路:
- 将图片url转为Image对象
- 将Image对象绘制到Canvas上
- 将Canvas对象转为Base64
实现代码
// Image对象转base64 function imageToBase64(image) { let canvas = document.createElement('canvas') let width = image.width let height = image.height canvas.width = width canvas.height = height let context = canvas.getContext('2d') context.drawImage(image, 0, 0, width, height) return canvas.toDataURL('image/png') } // 回调方式 function urlToBase64(url, callback = null) { let image = new Image() image.setAttribute('crossOrigin', 'Anonymous') image.src = url + '?v=' + Math.random() image.onload = function () { let dataURL = imageToBase64(image) if (callback) { callback(dataURL) } } } // Promise方式 function urlToBase64Async(url) { return new Promise((resolve, reject) => { urlToBase64(url, (data) => { resolve(data) }) }) } (async () => { let image_url ='https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg' const dataURL = await urlToBase64Async(image_url) console.log(dataURL) // data:image/png;base64,iVBORw0KGgoAAAANSU })()
需要注意的是:
浏览器中有跨域问题的存在,所以浏览器端处理的图片地址,需要确保允许跨域
参考