Using a sprite sheet with multiple sprites

2019-09-21 02:31发布

Hey guys so I have a sprite sheet with multiple sprites that I want to use to animate a website using canvas.

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. How would I go about retrieving and animating the correct frames?

P.S I'm using javascript.

1条回答
Viruses.
2楼-- · 2019-09-21 03:13

Retrieving and Playing multiple sprites on a spritesheet

Retrieving: Create an object defining each sprite's x,y,width,height and save the objects in an array

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.

Playing a frame: Use the clipping verision of context.drawImage to "play" a sprite frame:

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

// 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
  • the new (better) way is with requestAnimationFrame
查看更多
登录 后发表回答