So I'm writing a game on JS Canvas and I'm making my own GUI from scratch. To do so, I made a button
object with fields x, y, width, height
and intersects(click_event)
. For some reason, when I directly put this expression for x
, it returns NaN
even though the expression works everywhere else.
It's just a simple game on Canvas. I know I could probably use some dirty trick to work around it, but I want to keep my code clean. I just don't understand why this wouldn't work.
var button = {
height:80,
width:200,
x:canvas.width/2 - this.width/2, //this is the problem
y:200,
//other stuff
};
console.log(button.x); //this prints "NaN"
console.log(canvas.width/2 - button.width/2); //prints correct num
The canvas width is 1000, so 1000 / 2 - 200 / 2 should equal 400, which it does when called inside console.log
.
But when I put it inside button.x
it evaluates to NaN
.