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);
}
}
謝謝您的幫助!
對不起,我寫了一篇新文章,因爲沒有人回答舊文章。
需要注意的是'$這個== obj' – Eric
非常感謝你。謝謝你,我明白這個問題。 – L99
@Eric對,謝謝!請參閱更新。 – ComFreek