[英]Javascript loop not working properly (FRAME UPDATE LOOP)
當我嘗試運行以下代碼時,在控制台日志上,我得到“ Done !!”,而不是
設置currentFrame = 0
sourceX = 0
假定有一個計數器,間隔為300毫秒,並更新“ currentFrame”和“ sourceX”變量。 但是,條件是真實的,除了“ Done !!”之外,它什么都不輸出。
以下是我的代碼:
var canvas = document.querySelector("canvas");
var drawingSurface = canvas.getContext("2d");
var tileSheet = new Image();
tileSheet.src="frames.png";
var msperFrame = 300;
var interval;
SIZE=128;
tileSheet.addEventListener("load",loadHandler,false);
var monster={
frames:6,
SIZE:128,
currentFrame:0,
sourceX:0,
sourceY:0,
updateAnimation: function(){
var self=this;
if(self.currentFrame <= self.frames){
self.sourceX = self.currentFrame*this.SIZE;
console.log("Current Frame: "+self.currentFrame+"\nSourceX: "+self.sourceX);
self.currentFrame++;
render();
}else{
console.log("Done!!");
window.clearInterval(interval);
}
}
};
function loadHandler(){
interval = window.setInterval(monster.updateAnimation,msperFrame);
}
function render(){
drawingSurface.drawImage(tileSheet,
monster.sourceX,monster.sourceY,monster.SIZE,monster.SIZE,
0,0,monster.SIZE,monster.SIZE);
}
現在,這是一個有趣的錯誤:-)
您的問題是this
:當通過setTimeout
或setInterval
運行時,它默認為window
而不是monster
。 嘗試這個:
interval = window.setInterval(function(){monster.updateAnimation();},msperFrame);
通過將其包裝在匿名函數中,應該沒問題。 您將獲得“完成!” 因為if (window.currentFrame <= window.frames)
中的兩個屬性均未定義。
旁注:
您正在使用this.SIZE
而不是self.SIZE
。
每個渲染循環300 ms可能會產生大塊的動畫。
window.setInterval(monster.updateAnimation,msperFrame);
實際上將被翻譯成
window.setInterval(function(){
var self=this; //here 'this' is window
if(self.currentFrame <= self.frames){
self.sourceX = self.currentFrame*this.SIZE;
console.log("Current Frame: "+self.currentFrame+"\nSourceX: "+self.sourceX);
self.currentFrame++;
render();
}else{
console.log("Done!!");
window.clearInterval(interval);
}
},msperFrame);
此函數將從global
范圍或window
范圍運行。 因此, this
將是window
對象。
當你做
window.setInterval(function(){monster.updateAnimation();},msperFrame);
正如@erik建議的那樣http://jsfiddle.net/Vn3s7/
function(){monster.updateAnimation();}
將在window
范圍內運行。 由於monster
是可以作為global
的window
范圍內,“moster.updateAnimation”可用,並且將被用this
指針作為monster
本身。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.