[英]javascript image onload function never called
在javascript中加載圖片時遇到問題。 似乎從未調用.onload函數,因此該圖片未標記為已加載。 你能幫我嗎?
這是代碼:
//image loader
var img = function (source){
this.loaded = false;
this.image = new Image();
this.image.onload = function () {
this.loaded = true;
};
this.image.src = source;
}
//default component definition
var component = function (x, y){
this.x = x;
this.y = y;
this.draw = function (offsetX, offsetY, img){
if(img.loaded){
ctx.drawImage(img.image,
this.x + offsetX,
this.y + offsetY,
img.image.width, img.image.height);
}
}
}
謝謝
上下文1
this.image.onload = function () {
this.loaded = true;
};
this
指[object HTMLImageElement]
,而不是img
實例。
上下文2
現在,將代碼更改為:
this.image.onload = function () {
this.loaded = true;
}.bind(this);
當您執行new img("http://serban.ghita.org/imgs/serban.jpg");
, this
將引用您的[object Object]
。
上下文#3
現在,如果您執行img("http://serban.ghita.org/imgs/serban.jpg");
,沒有new
, this
將是指[object Window]
。
解
這取決於上下文this
。
bind
改變它 var _this = this;
然后使用_this.loaded = true;
內部onload
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.