[英]Javascript Image.onload callback to object function
這讓我瘋了 - 我已經四處轉圈,這並不令人高興。 我正在加載多個動態圖像,並有一個簡單的Javascript對象,我為每個圖像實例化,並且一旦異步加載,它就有一個回調來渲染圖像。
我已經驗證回調代碼在獨立的基礎上工作得很好(即,我可以在圖像加載后手動調用回調,並且圖像被正確渲染),並且我已經驗證了圖像本身是成功加載(通過切換對象的回調以獲得簡單的一行記錄功能),但是當我嘗試將它們全部綁定在一起時,回調顯然永遠不會被調用。
我對JS比較陌生,我懷疑我遺漏了一些關於對象內部函數定義方式的基本信息,但是盡管有很多谷歌搜索,卻無法解決問題。
請有人能告訴我我的方式錯誤嗎?
function ImageHolder(aX,aY,aW,aH, anImageURL) {
this.posx=aX;
this.posy=aY;
this.posw=aW;
this.posh=aH;
this.url=anImageURL;
this.myImage = new Image();
this.myImage.onload=this.onload;
this.myImage.src=anImageURL;
this.onload=function() {
try {
var d=document.getElementById("d");
var mycanvas=d.getContext('2d');
mycanvas.drawImage(this.myImage, this.posx, this.posy, this.posw, this.posh);
} catch(err) {
console.log('Onload: could not draw image '+this.url);
console.log(err);
}
};
}
您有兩個問題:首先, this.onload
未在您將其分配給圖像的位置定義。 您可以通過錯過將onload
處理函數存儲this
屬性的階段來解決此this
。 第二個問題是,當onload
處理函數時, this
不會被設置為你認為的那樣(事實上,它是對剛剛加載的Image
對象的引用)。 你需要存儲到當前的基准ImageHolder
對象,並使用它,而不是this
事件處理函數中。
新代碼:
var that = this;
this.myImage = new Image();
this.myImage.onload=function() {
try {
var d=document.getElementById("d");
var mycanvas=d.getContext('2d');
mycanvas.drawImage(that.myImage, that.posx, that.posy, that.posw, that.posh);
} catch(err) {
console.log('Onload: could not draw image '+that.url);
console.log(err);
}
};
this.myImage.src = anImageURL;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.