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?
PS I'm using javascript.
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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.