I want to access img property in onload function how can i do this ? i added img property to Picture object and calling onload function with scope of Picture object, still i can not access this.img.
我想在onload函数中访问img属性我该怎么做?我将img属性添加到Picture对象并使用Picture对象的范围调用onload函数,仍然无法访问this.img。
// picture
function Picture(x, y, w, h, imgurl){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.imgurl = imgurl;
this.draw = drawPic;
this.overcheck = overRect;
} // end picture
function drawPic(){
this.img = new Image(); // add img to this scope
this.img.src = this.imgurl;
this.img.onload = function(){
//ctx.drawImage(this.image, this.that.x, this.that.y, this.that.w, this.that.h);
ctx.drawImage(this.img, this.x, this.y, this.w, this.h); //error
} // end onload
this.img.onload.call(this);
} // end drawPic
2 个解决方案
#1
Use a reference to this
使用对此的引用
function drawPic() {
var self = this;
this.img = new Image();
this.img.src = this.imgurl;
this.img.onload = function() {
ctx.drawImage(self.img, self.x, self.y, self.w, self.h);
};
}
#2
I think you'll have to define the function inside the object:
我想你必须在对象中定义函数:
function Picture(x, y, w, h, imgurl){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.imgurl = imgurl;
this.draw = function(){
this.img = new Image(); // add img to this scope
this.img.src = this.imgurl;
this.img.onload = function(){
ctx.drawImage(this.img, this.x, this.y, this.w, this.h); //error
} // end onload
this.img.onload.call(this);
} // end drawPic;
this.overcheck = overRect;
} // end picture
#1
Use a reference to this
使用对此的引用
function drawPic() {
var self = this;
this.img = new Image();
this.img.src = this.imgurl;
this.img.onload = function() {
ctx.drawImage(self.img, self.x, self.y, self.w, self.h);
};
}
#2
I think you'll have to define the function inside the object:
我想你必须在对象中定义函数:
function Picture(x, y, w, h, imgurl){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.imgurl = imgurl;
this.draw = function(){
this.img = new Image(); // add img to this scope
this.img.src = this.imgurl;
this.img.onload = function(){
ctx.drawImage(this.img, this.x, this.y, this.w, this.h); //error
} // end onload
this.img.onload.call(this);
} // end drawPic;
this.overcheck = overRect;
} // end picture