Unit 7 · JavaScript

7.10.2Sprite sheet animation

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.

hero.png (one image, 4 × 2 frames of 64 × 64 px)frame 0frame 1frame 2frame 3row 0: walk rightrow 1: walk leftsx = frame × 64 = 128, sy = row × 64 = 0canvasdx, dy, dWidth, dHeightwhere to paint it
drawImage cuts one frame from the sheet (source rectangle) and paints it on the canvas (destination)

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 canvas
JavaScript
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);