我正在开发一个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);
}
}
感谢您的帮助!
对不起,但我写了一篇新帖子,因为没有人回答旧帖子。
答案 0 :(得分:2)
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
- 上下文存在一个陷阱。 this
回调函数中的onload
未引用 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
不再引用 Image 对象了!
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);