this.image.width / number得0

时间:2013-02-16 03:08:11

标签: javascript

我正在尝试使用图像宽度计算精灵的宽度,但数字总是为0,为什么会这样?

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和spritesheet.spriteHeight总是产生0.我把问题逼到'this.image.width',因为如果我手动放入图像的宽度就可以了。

this.spriteWidth = 880 / this.numFramesX;

而不是

this.spriteWidth = this.image.width / this.numFramesX;

如果我使用控制台中的对象计算它,它也有效:

spritesheet.image.width / spritesheet.numFramesX

收益率110

jsfiddle

1 个答案:

答案 0 :(得分:2)

那怎么样?

window.onload = function () {
    console.log('Image has been loaded');
    image.src = 'dance.png';
    spritesheet = new SpriteSheet(image, 8, 10, 80);
}