图片转base64编码
toBase64(imgUrl) { // 一定要设置为let,不然图片不显示 const image = new Image(); // 解决跨域问题 image.setAttribute("crossOrigin", "anonymous"); const imageUrl = imgUrl; image.src = imageUrl; console.log(image); // image.onload为异步加载 image.onload = () => { var canvas = document.createElement("canvas"); canvas.width = image.width; canvas.height = image.height; var context = canvas.getContext("2d"); context.drawImage(image, 0, 0, image.width, image.height); var quality = 0.8; // 这里的dataurl就是base64类型 // 使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png,因为压缩成png后base64的字符串可能比不转换前的长! const dataurl = canvas.toDataURL("image/jpeg", quality); console.log(dataurl); //将编码后的地址赋给src(本为中我的图片src变量为avatarUrl) this.avatarUrl = dataurl; }; },