2014-03-30 42 views
0

我正在研究JavaScript遊戲,我遇到了一個對象的兩個屬性有問題。
屬性x和y是NaN,但我不明白爲什麼。現在我張貼代碼:
NaN的JavaScript問題

var canvas; 
var ctx; 
var canvasH = 480; 
var canvasW = 960; 

window.onload = function() { 
canvas = document.getElementById("canvas"); 
ctx  = canvas.getContext('2d'); 

canvas.width = canvasW; 
canvas.height = canvasH; 

drawCanvas(); 
} 

功能drawCanvas():

function drawCanvas() { 

ctx.fillStyle = "#000000" 
ctx.fillRect(0, 0, canvasW, canvasH); 
} 

這裏的構造我的對象:

function SpaceCraft() { 

var obj = this; 

this.texture = new Image(); 
this.texture.src = "img/spacecraft.png"; 
this.texture.onload = function() { 
    obj.w = this.width; 
    obj.h = this.height; 
} 

this.x = canvasW/2 - obj.w/2; //PROBLEM IS NaN 
this.y = canvasH - obj.h;   //PROBLEM IS NaN 

//Methods 

//Draw 

this.draw = function() { 
    ctx.drawImage(this.texture, this.x, this.y); 
} 
} 

謝謝您的幫助!

對不起,我寫了一篇新文章,因爲沒有人回答舊文章。

回答

2

obj.wobj.h在您使用它們時未設置。

您的代碼:

this.texture = new Image(); 
this.texture.src = "img/spacecraft.png"; 
this.texture.onload = function() { 
    obj.w = this.width; 
    obj.h = this.height; 
} 

// the following lines won't get executed after the onload event 
// they will be executed immediately after the assignment of the onload event 
this.x = canvasW/2 - obj.w/2; //PROBLEM IS NaN 
this.y = canvasH - obj.h;   //PROBLEM IS NaN 

obj.wobj.h將獲得分配紋理加載後,但是,你立刻從上面摘錄的最後兩行使用它們。

您必須將這些行移動到回調函數.onload中,以確保變量寬度和高度的存在。

此外,還有一個有關this –上下文的陷阱。 thisonload回調函數中沒有引用航天器的實例。
既然你已經有一個變量obj這是指你的航天器情況下,只需要使用它:

this.texture = new Image(); 
this.texture.src = "img/spacecraft.png"; 

this.texture.onload = function() { 
    obj.w = this.width; 
    obj.h = this.height; 
    obj.x = canvasW/2 - obj.w/2; //PROBLEM IS NaN 
    obj.y = canvasH - obj.h;   //PROBLEM IS NaN 
} 

另一種選擇是bind回調函數,以特定的上下文。
請注意,您必須將this.width/height替換爲this.texture.width/height,因爲this不會引用圖片對象了!

this.texture = new Image(); 
this.texture.src = "img/spacecraft.png"; 

this.texture.onload = (function() { 
    // obj = this due to the use of bind() 

    this.w = this.texture.width; 
    this.h = this.texture.height; 
    this.x = canvasW/2 - this.w/2; //PROBLEM IS NaN 
    this.y = canvasH - this.h;   //PROBLEM IS NaN 
}).bind(this); 

+0

需要注意的是'$這個== obj' – Eric

+0

非常感謝你。謝謝你,我明白這個問題。 – L99

+0

@Eric對,謝謝!請參閱更新。 – ComFreek