我正在开发一款 JavaScript 游戏,但我的一个对象的两个属性出现了问题。
属性 x 和 y 是 NaN,但我不明白为什么。现在我发布代码:
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.w
和 obj.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.w
和 obj.h
将在纹理加载后分配,但是,您可以立即在上面摘录的最后两行中使用它们。
您必须将这些行移至回调函数.onload
中,以便确保变量 width 和 height 的存在。
此外,还有一个关于 this
的陷阱——上下文。 onload
回调函数中的 this
并不引用 Spacecraft 的实例。
由于您已经有一个变量 obj
引用您的 Spacecraft 实例,因此只需使用它:
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);
关于JavaScript 与 NaN 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22744684/