如何使用Vue将url图像转换为base64

时间:2018-05-29 04:08:46

标签: vue.js vuejs2 base64

我试图从Facebook登录转换图片网址。我希望使用Vue来完成这项任务。

    getDataUri(url, callback){
          let image = new Image()

          image.onload = () => {
              let canvas = document.createElement('canvas');
              canvas.width = this.naturalWidth
              canvas.height = this.naturalHeight
              canvas.getContext('2d').drawImage(this, 0, 0)
              callback(canvas.toDataUrl('image/png').replace(/^data:image\/(png|jpg);base64,/, ''))
              callback(canvas.toDataURL('image/png'))
          }

          image.src = url
      },

  retrivePhoto(id){
    FB.api('/'+id+'/picture?redirect=false&height=120&width=120','GET',{},
      function(response) {
        console.log(this.getDataUri(response.data.url));
      });
    },

当我尝试运行代码时,我收到了此javascript错误

  

all.js:108 Uncaught TypeError:this.getDataUri不是函数

1 个答案:

答案 0 :(得分:0)

上下文已更改,请使用箭头函数或Function.prototype.bind:

  FB.api('/'+id+'/picture?redirect=false&height=120&width=120',
    'GET',
    {},
    response=>{
      console.log(this.getDataUri(response.data.url));
    }
  );

  FB.api('/'+id+'/picture?redirect=false&height=120&width=120',
    'GET',
    {},
    function(response){
      console.log(this.getDataUri(response.data.url));
    }.bind(this)
  );