自调用函数结构原型不起作用

self invoke function fabric prototype dont work

(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);

错误:

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)

我的意图是在我的结构函数中使用原型,但它一直有问题,我无法让它显示在我的 canvas 上。我想可能是因为我正在使用自调用函数。

有没有办法把我的变量放在自调用函数中,我可以在我的原型函数 fabric 中访问它。

您的问题是在 fabric.Image.fromURL() 的回调中,this 未定义为 UpdateCanvas。参见 How to access the correct `this` context inside a callback?

在你的回调函数之外设置一个等于 this 的变量,就像在你的回调函数中 this JSFiddle will fix your problem. Alternatively you can use bind 绑定一个不同的 this

工作代码:

(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);