JavaScript issue with NaN

JavaScript issue with NaN

本文关键字:NaN with issue JavaScript      更新时间:2023-09-26

我正在开发一个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.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的陷阱——背景。 onload回调函数中的this不引用 Spacecraft.
的实例由于您已经有一个引用您的航天器实例的变量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  
}
<小时 />

另一种选择是将回调函数绑定到特定上下文。请注意,您必须将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);