在画布中动画精灵帧

时间:2011-10-27 00:42:37

标签: javascript canvas

我正在使用canvas元素制作一个小平台游戏,但我在制作使用精灵的最佳方法时遇到了麻烦。

Canvas不支持动画GIF,所以我不能这样做,所以我为我的动画精灵制作了一个电影条,让人觉得角色正在移动。像这样:http://i.imgur.com/wDX5R.png

以下是相关代码:

function player() {

    this.idleSprite = new Image();
    this.idleSprite.src = "/game/images/idleSprite.png";
    this.idleSprite.frameWidth = 28;
    this.idleSprite.frameHeight = 40;
    this.idleSprite.frameCount = 12;

    this.runningSprite = new Image();
    this.runningSprite.src = "/game/images/runningSprite.png";
    this.runningSprite.frameWidth = 34;

    this.update = function() {

    }

    var frameCount = 1;
    this.draw = function() {
        c.drawImage(this.idleSprite, this.idleSprite.frameWidth * frameCount, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight, 0, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight);
        if(frameCount < this.idleSprite.frameCount - 1) { frameCount++; } else { frameCount = 0; }
    }
}

var player = new player();

正如您所看到的,我正在定义空闲精灵及其帧宽和帧数。然后在我的draw方法中,我使用这些属性告诉drawImage方法绘制哪个帧。一切正常,但我对draw方法之前定义的frameCount变量不满意。看起来...... hacky和丑陋。如果没有跟踪绘制方法之外的帧,人们会知道如何实现相同的效果吗?或者甚至是将动画精灵绘制到画布上的更好的替代方案也不错。

感谢。

1 个答案:

答案 0 :(得分:1)

您可以根据当前时间的某些部分选择帧,例如

this.draw = function() {
    var fc = this.idleSprite.frameCount;
    var currentFrame = 0 | (((new Date()).getTime()) * (fc/1000)) % fc;
    c.drawImage(this.idleSprite, this.idleSprite.frameWidth * currentFrame, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight, 0, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight);
}

这将为您提供一秒钟的动画(1000是毫秒值)。根据您的帧速率和动画,这可能看起来不稳定,但它不依赖于持久性计数器。

相关问题