A sprite is a 2D image of a character or object. A sprite sheet is a single image containing many frames of an animation arranged in a grid. Showing the frames one after another makes the character appear to walk. One file loads faster than many.
Drawing a part of an image uses the long form of drawImage:
JavaScript
ctx.drawImage(image, sx, sy, sWidth, sHeight, // source rectangle cut from the sheet
dx, dy, dWidth, dHeight); // destination on the canvasJavaScript
const sheet = new Image();
sheet.src = 'images/hero.png'; // free sheets: kenney.nl, opengameart.org, itch.io
const FRAME_W = 64, FRAME_H = 64; // size of one frame
const FRAMES = 4; // frames per row
let frame = 0; // current frame number
let tick = 0; // counts game loop passes
const FRAME_DELAY = 8; // change frame every 8 loops (controls speed)
function animate(moving) {
if (!moving) { frame = 0; return; } // standing still shows frame 0
tick++;
if (tick >= FRAME_DELAY) {
tick = 0;
frame = (frame + 1) % FRAMES; // 0,1,2,3,0,1,...
}
}
function drawPlayer(p) {
ctx.drawImage(
sheet,
frame * FRAME_W, p.row * FRAME_H, FRAME_W, FRAME_H, // which frame to cut
p.x, p.y, p.w, p.h // where to draw
);
}Do not start the game until the image is loaded: sheet.onload = () => requestAnimationFrame(loop);