0
(function (window, $, undefined){

'use strict';


// Main canvas
var mainCanvas = new fabric.Canvas("imageCanvas");


function UpdateCanvas(){
this.canvas = mainCanvas;
}

UpdateCanvas.prototype.img = function (src){
  this.canvas.clear();

  fabric.Image.fromURL(src, function(oImg) {
    oImg.setWidth(500);
    oImg.setHeight(400);
    oImg.left = ((this.canvas.width/2)-(oImg.width/2));
    oImg.top = 50;
    oImg.selectable = false;
    this.canvas.add(oImg);
    this.canvas.renderAll();
  });
}


})(window, jQuery);

Error:

ncaught TypeError: Cannot read property 'canvas' of undefined
    at design-application.js:30
    at fabric.min.js:5
    at HTMLImageElement.i.onload (fabric.min.js:1)

my intention is to use prototype in my fabric function , but it keep having problem and i cant make it show on my canvas. i think maybe is because i am using self invoke function.

is there a way to put my variable at self invoke function and i can access it at my prototype function fabric .

user3233074
  • 519
  • 4
  • 18

1 Answers1

0

Your problem is that within your callback for fabric.Image.fromURL(), this is not defined to be UpdateCanvas. See How to access the correct `this` context inside a callback?.

Setting a variable to equal this outside your callback function like in this JSFiddle will fix your problem. Alternatively you can use bind on your callback to bind a different this

Working code:

(function (window, $, undefined){

'use strict';


// Main canvas
var mainCanvas = new fabric.Canvas("imageCanvas");

function UpdateCanvas(){
this.canvas = mainCanvas;
}

UpdateCanvas.prototype.img = function (src){
  this.canvas.clear();
    var that = this;
  fabric.Image.fromURL(src, function(oImg) {
    oImg.setWidth(500);
    oImg.setHeight(400);
    oImg.left = ((that.canvas.width/2)-(oImg.width/2));
    oImg.top = 50;
    oImg.selectable = false;
    that.canvas.add(oImg);
    that.canvas.renderAll();
  });
};

var test = new UpdateCanvas(mainCanvas);
test.img("https://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png");
})(window);
Community
  • 1
  • 1
Josh
  • 338
  • 2
  • 13