(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)
我的意图是在我的面料功能中使用原型,但它一直有问题,我不能让它显示在我的画布上。我想也许是因为我正在使用自我调用功能。
有没有办法将我的变量放在自调用函数中,我可以在我的原型函数结构中访问它。
答案 0 :(得分:0)
您的问题是,在fabric.Image.fromURL()
的回调中,this
未定义为UpdateCanvas
。请参阅How to access the correct `this` context inside a callback?。
将变量设置为在this JSFiddle之外的回调函数之外等于this
将解决您的问题。或者,您可以在回调中使用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);