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