I’m starting on a small HTML5 game and it’s the first one I’m doing on. At the moment, I’m creating a function that holds variables, I don’t really know what it’s called, I just remember how to do it from a tutorial. Anyway, I’m trying to set up some of the variables using ‘this’ but it doesn’t seem to get a value. Here’s the code that I think is causing the problem:
function ship() {
this.width = 100;
this.height = 75;
this.drawX = gameWidth/2 - this.width/2;
this.drawY = gameHeight + this.height;
}
this.drawX and Y however, seem to not get a value. Also, I’m sure that gameHeight and gameWidth have a value.
Edit: Here is the draw function and rest of the code:
var player = new ship();
var gameWidth = canvasShip.width;
var gameHeight = canvasShip.height;
var sprites = new Image();
sprites.src = 'images/spriteSheet.png';
var canvasPlayer = document.getElementById('canvasShip');
var ctxPlayer = canvasPlayer.getContext('2d');
//Clear any canvas
function clearCtx(canvas) {
canvas.clearRect(0,0,gameWidth,gameHeight);
}
//Ship object, the player
function ship() {
this.width = 100;
this.height = 75;
console.log(gameWidth,gameHeight);
this.drawX = gameWidth/2 - this.width/2;
this.drawY = gameHeight + this.height;
}
ship.prototype.draw = function() {
clearCtx(ctxPlayer);
ctxPlayer.drawImage(sprites,0,0,this.width,this.height,this.drawX,this.drawY, this.width, this.height);
}
This part in your code looks fishy:
Inside the constructor of
ship(), the values ofgameWidthandgameHeightwould beundefined.Reversing the statements should work as expected:
This is the way that JavaScript sees your code:
The declaration of
ship()gets moved up in a process sometimes referred to as “hoisting“, making it more obvious why it behaves this way.