Lesson 8 of 10

Sprite sheets

Goal

Pick which cell to draw and when to draw it

01

Explanation

An animated character in a pixel-art game is one big image called a sprite sheet. It's split into a grid of equal cells, each holding one snapshot of the motion, and animating the character means drawing a different cell at each moment.

When you call drawImage with nine arguments, it cuts out part of the source image and draws it, like this: drawImage(sheet, sx, sy, sw, sh, dx, dy, dw, dh). So all you need to know is where cell number frame sits. Its column is the remainder when you divide its number by the number of columns, and its row is the quotient rounded down.

The common mistake is to move to the next frame on every requestAnimationFrame call, which makes the character run about two and a half times as fast on a 144 Hz screen as on a 60 Hz one. The right way is to work out the frame number from the elapsed time: multiply the seconds by fps and round down, then take the remainder after dividing by count so it wraps back to the first frame after the last.

02

Your task

Write frameRect(frame, cols, w, h) to return { sx, sy, sw, sh } for the cell that holds frame number frame in a sheet with cols columns, where each cell is w × h. Then write frameAt(t, fps, count) to return the frame number after t seconds. The sheet itself is drawn in code on a hidden canvas, so there are no images to load from the internet.

Checks

5 checks
  1. Frames follow one another along the first row
  2. After the last column it moves to the next row
  3. A rectangular cell uses w for columns and h for rows
  4. The frame number comes from the time and fps
  5. It wraps back to the first frame after the last
03

Hints

0/3
Track lessons0 of 10 done

Build a real canvas game that runs in any browser, and learn the game loop, movement, collisions and scoring along the way.

Intermediate level, 10 lessons, 2.5 hours in total.

index.html
Preview
index.html100%
–/5

Press “Run and check” to grade your code.

5 checks listed under “Your task”.

Track lessons0 of 10 done

Build a real canvas game that runs in any browser, and learn the game loop, movement, collisions and scoring along the way.

Intermediate level, 10 lessons, 2.5 hours in total.