一、封装代码

 getBase64(url, callback) {
      var Img = new Image(),
      dataURL = '';
      Img.src = url +"?v=" + Math.random();
      Img.setAttribute("crossOrigin", 'Anonymous') 
      Img.onload = function () { 
          var canvas = document.createElement("canvas"), 
          width = Img.width, 
          height = Img.height;
          canvas.width = width;
          canvas.height = height;
          canvas.getContext("2d").drawImage(Img, 0, 0, width, height); 
          dataURL = canvas.toDataURL('image/jpeg'); 
          callback ? callback(dataURL) : null; 
      };
    },

二、调用

this.getBase64(url, (data) => {
     // 将url图片转为了base64的data
})

// 或者
getBase64(url, handleBase64)
// handleBase64方法里的形参拿到base64


问题:同时要转多个图片怎么弄呢?
添加方法

toBase64(url){
      return new Promise((resolve,reject)=>{
        this.getBase64(url, (data) => {
          resolve(data)
        })
      })
},

然后

Promise.all([
        this.toBase64(url1),
        this.toBase64(url2)
]).then(res=>{
        // 将两个图片地址分别返回base64
        // res[0]
        // res[1]
})

Logo

前往低代码交流专区

更多推荐