Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

javascript - 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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...