Javascript 和 HTML5 Canvas Sprite

标签 javascript html html5-canvas sprite

我正在关注关于 Sprite 的教程: http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/ 我现在有一个 Sprite 在工作,但我喜欢 Sprite 有不止一个动画。这些动画应该取决于这个 Sprite 应该有的特定状态。

我喜欢做的是在旧的 Apple 游戏空降中创建伞兵。有关示例,请参见 http://www.youtube.com/watch?v=pYujWCNUuNw 你看到那些士兵从直升机上掉下来。当它们在地面上时,它们会静止一会儿,然后不时地开始行走。

这是我的 Sprite 方法:

function sprite(options) {
var that = {},
frameIndex = 0,
tickCount = 0, ticksPerFrame = options.ticksPerFrame || 0, numberOfFrames = options.numberOfFrames || 1;
that.x = options.x, that.y = options.y,
that.context = options.context;
that.width = options.width;
that.height = options.height;
that.image = options.image;

that.update = function() {
    tickCount += 1;

    if (tickCount > ticksPerFrame) {

        tickCount = 0;

        // If the current frame index is in range
        if (frameIndex < numberOfFrames - 1) {
            // Go to the next frame
            frameIndex += 1;
        } else {
            frameIndex = 0;
        }
    }
};

that.render = function() {
    // Draw the animation
    that.context.drawImage(that.image,
        frameIndex * that.width / numberOfFrames,
        0,
        that.width / numberOfFrames,
        that.height, that.x,
        that.y,
        that.width / numberOfFrames,
        that.height);
};
return that;
}

我怎样才能让这个 Sprite 有那些额外的动画选项?

谢谢

最佳答案

您可以使用指向每个区域的偏移值:

var offsets = [0, animation2x, animation3x, ...];

然后,当您使用表示偏移数组索引的整数值更改动画类型时,您可以执行以下操作:

var animation = 1;

hat.context.drawImage(that.image,
    offsets[animation] + frameIndex * that.width / numberOfFrames,
    ....

您可能需要或想要向偏移量添加其他信息,这些信息也可能是包含帧数、大小等的对象。

一个伪示例可能如下所示:

var offsets = [{offset:0, frames:12, w:100, h:100},
               {offset:1200, frames:7, w: 90, h:100},
               ...];
...

var offset = offsets[animation];

hat.context.drawImage(that.image,
    offset.offset + frameIndex * offset.w / offset.frames,
    ....

if (frameIndex > offset.frames) ...

您可以选择为每个动画使用不同的图像并使用相同的方法,而是存储带有指向您要使用的图像的指针的对象。

关于Javascript 和 HTML5 Canvas Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19406778/

相关文章:

javascript - 有没有办法重用 ImageData 来减少 GC 事件?

javascript - 错误 TS7017 : Index signature of object type implicitly has an 'any' type in form validation angular 2

javascript - onchange 事件不接受我的 javascript 代码

javascript - 无法从内部隐藏模态框

php - 动态添加的表单字段 - pdo php mysql

javascript - 我在 Canvas 上的 EaselJS 位图在 Firefox 中正确呈现,但(有时)没有缩放并在 Chrome 中占据整个 Canvas ?

javascript - 我可以在 HTML5 Canvas 中创建图形形状对象吗以及当用户将鼠标悬停在形状上时如何将光标显示为指针

javascript - 如何将无序列表放置在一个圆圈中?

html - 为什么这些图片无法在移动设备上加载? - HTML/CSS

css - 使用标签元素时,输入组插件高度无法正常工作