0

I am trying to call the function save after I make sure the image is completely loaded, but it does not work!

In <script>:

//change image width and heignt (100*100).
var canvas = document.createElement('canvas');
var width = 100; var height = 100;
canvas.width = 100; canvas.height = 100;
var imgTile = new Image(); imgTile.src = this.cropImg;
imgTile.onload = function(){
  canvas.getContext('2d').drawImage(imgTile, 0, 0, width, height);
  var img_data = canvas.toDataURL('image/jpeg');
  console.log("img_data: " + img_data);
  this.New_cropImg = img_data;
  this.showImage = true;
  this.save(this.New_cropImg);
};

and function save is already defined and works perfectly outside the onload function.

How can I solve this problem?

Mohd Ali
  • 145
  • 1
  • 3
  • 16
  • 1
    This is because "this.save" is invoked from the context of imgTile. I think you should call save without "this" and make sure it is hoisted before the onload is invoked – Sumodh Nair Aug 24 '18 at 10:21
  • @BenFortune I didn't find anything there to help me, I am using VueJs to implement the code, not pure javascript. save function is defined in the method section, and even the method that I call save function from it it is defined there. – Mohd Ali Aug 24 '18 at 11:03
  • @SumodhNair I tried to remove `this` and run the code, it said `Uncaught ReferenceError: save is not defined`. – Mohd Ali Aug 24 '18 at 11:03

1 Answers1

1

Your problem is (as stated in the comments) that your context within the function is wrong

imgTile.onload = function(){
  canvas.getContext('2d').drawImage(imgTile, 0, 0, width, height);
  var img_data = canvas.toDataURL('image/jpeg');
  console.log("img_data: " + img_data);
  this.New_cropImg = img_data;
  this.showImage = true;
  this.save(this.New_cropImg);
}.bind(this);

a simple .bind(this) can solve it for you.

Frnak
  • 6,601
  • 5
  • 34
  • 67