JavaScript issue with NaN
JavaScript issue with NaN
我正在开发一个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
中,这样你才能确保变量宽度和高度的存在。
此外,还有一个关于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);
相关文章:
- Fighting with FRP
- issue with FB.Event.subscribe
- geolocation-marker.js conflict with markerclusterer.js
- Angular 2.0 with JavaScript or TypeScript?
- 为什么不推荐使用“with”?是否有更好或其他方法可以“下降”到对象的命名空间
- JavaScript NaN equvialence
- WebComponentsJS with IE10
- 指令的模板必须只有一个根元素:With restrict E&替换true
- 如何为排除无穷大和NaN的数字声明Flow类型
- 为什么我在这个javaScript代码中使用NaN
- 如何防止Math.max()返回NaN
- timeago.js with datatable and PHP
- Ajax and Json with Rails
- errors with Javascript try catch
- how to split a string with ','
- Understanding Javascript scope with "var that = this&qu
- JavaScript NaN with HTML
- NaN with 6 calculations
- NaN assigned with innerHTML
- JavaScript issue with NaN