Reputation: 1243
I'm trying to calculate the width of a sprite using the image width, but the number always comes out as 0, why is that?
function SpriteSheet(image, numFramesX, numFramesY, totalFrames) {
this.image = image;
this.numFramesX = numFramesX;
this.numFramesY = numFramesY;
this.totalFrames = totalFrames;
this.spriteWidth = this.image.width / this.numFramesX;
this.spriteHeight = this.image.height / this.numFramesY;
}
image.onload = function() {
console.log('Image has been loaded');
}
image.src = 'dance.png';
spritesheet = new SpriteSheet(image, 8, 10, 80);
spritesheet.spriteWidth and spritesheet.spriteHeight always yields 0. I cornered the problem to 'this.image.width' since it works if I put in the width of the image manually.
this.spriteWidth = 880 / this.numFramesX;
instead of
this.spriteWidth = this.image.width / this.numFramesX;
It also works if I calculate it using the object in the console:
spritesheet.image.width / spritesheet.numFramesX
yields 110
Upvotes: 0
Views: 63
Reputation: 4514
How about that?
window.onload = function () {
console.log('Image has been loaded');
image.src = 'dance.png';
spritesheet = new SpriteSheet(image, 8, 10, 80);
}
Upvotes: 2