Bruno Justino Praciano
Bruno Justino Praciano

Reputation: 552

How to convert url image into base64 using Vue

I'm trying to convert a image url from facebook login. I'd like to this task using 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));
      });
    },

When I tried to run the code, I got this javascript error

all.js:108 Uncaught TypeError: this.getDataUri is not a function

Upvotes: 0

Views: 4715

Answers (1)

jacky
jacky

Reputation: 1446

The context changed, use arrow functions or Function.prototype.bind to call getDataUri on the right context:

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

or

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

Upvotes: 1

Related Questions