图片资源在直接使用ajax请求时会出现跨域的问题,使用此方法来获取base64数据。如:使用前端裁剪工具时,大概率会出现此问题
function getBase64Img(url:){
let image = new Image()
image.src = url + "?" + Math.random()
// 对在线图片进行处理,需要图片服务器开启可跨域访问配置才行
image.crossOrigin = 'anonymous'
return new Promise((resolve, reject) => {
image.onload = function() {
let canvas = document.createElement("canvas")
canvas.width = image.width;
canvas.height = image.height;
let ctx = canvas.getContext("2d")
ctx.drawImage(image, 0, 0, image.width, image.height);
let dataURL = canvas.toDataURL("image/png");
resolve(dataURL)
}
})
}
调用示例
let img = ""
getBase64Img(‘http://resource.51weblove.com/blog/wordprerss/2019/03/2019032400535358.jpg’)
.then(res => {
img = res
})