简体   繁体   English

将精灵表与多个精灵一起使用

[英]Using a sprite sheet with multiple sprites

Hey guys so I have a sprite sheet with multiple sprites that I want to use to animate a website using canvas. 大家好,我有一个Sprite工作表,其中包含多个Sprite,我想使用它们来使用画布为网站制作动画。

However the problem I am having is I don't know how to go about reading in only the frames that I need. 但是我遇到的问题是我不知道如何只阅读所需的帧。

Example: 例:

1 1 1 2
2 2 2 2
3 3 4 4
4 4 4 4

Here I have 4 different sprites that I want to animate. 在这里,我要制作4种不同的精灵。 How would I go about retrieving and animating the correct frames? 我该如何检索正确的帧并制作动画呢?

PS I'm using javascript. PS我正在使用javascript。

Retrieving and Playing multiple sprites on a spritesheet 在Spritesheet上检索和播放多个Sprite

Retrieving: Create an object defining each sprite's x,y,width,height and save the objects in an array 检索:创建一个定义每个精灵的x,y,width,height的对象,并将对象保存在数组中

sprite1.push({x:0,y:0,width:20,height:30});
sprite1.push({x:20,y:0,width:20,height:30});
sprite1.push({x:40,y:0,width:20,height:30});

// do the same for sprites #2-4

Depending on your actual spritesheet, this code can be optimized--especially if the sprites are equally sized and spaced. 根据您的实际Spritesheet,可以优化此代码-尤其是在Sprite大小和间距均等的情况下。

Playing a frame: Use the clipping verision of context.drawImage to "play" a sprite frame: 播放帧:使用context.drawImage的剪切版本来“播放”一个精灵帧:

function playSpriteFrame(sprite,frameIndex,canvasX,canvasY){

    // get the current sprite from the sprite array

    var s=sprite[frameIndex];

    // draw that sprite on the canvas at canvasX/canvasY

    context.drawImage(
        spritesheet,                      // the spritesheet image
        s.x,s,y,s.width,s.height,         // clip from spritesheet
        canvasX,canvasY,s.width,s.height  // draw to canvas
    );

}

Example usage: Draw frame #2 of sprite1 at canvas 100,100 用法示例:在画布100,100上绘制sprite1的帧#2

// Remember arrays start at element 0 so frame#2 is at array element 1

playSpriteFrame(sprite1,1,100,100);

You didn't ask about how to create an animation loop, but here is starter info anyway: 您没有询问如何创建动画循环,但是无论如何这是入门信息:

  • the old way would be looping with setInterval or setTimer 旧方法将与setInterval或setTimer循环
  • the new (better) way is with requestAnimationFrame 新的(更好的)方式是使用requestAnimationFrame

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM