base64 是对图片字节内容进行的字符编码。以下代码定义了一个getBase64函数,它接受一个网络图片地址,函数通过new Promise api获取base64格式的图片。
function getBase64(url, width, height) { //传入图片路径,返回base64,使用getBase64(url).then(base64=>{},err=>{});
return new Promise((resolve) => {
const image = new Image();
image.crossOrigin = 'Anonymous';
image.src = url;
image.onload = function() {
const canvas = document.createElement('canvas');
canvas.width = width || image.width;
canvas.height = height || image.height;
canvas.globalAlpha = 1;
const context = canvas.getContext('2d')
context.drawImage(image, 0, 0);
const dataURL = canvas.toDataURL('image/png');
resolve(dataURL);
};
image.onerror = () => {
resolve('相片处理失败');
};
});
};
传入图片路径,返回base64,比如:
getBase64(url).then(base64=>{},err=>{});