TExcelTAD
Home › 2D Games with JavaScript & Canvas › Sprites & Sprite Sheets

Sprites & Sprite Sheets

A sprite is a small image that represents a game object: the hero, a coin, a bullet. A sprite sheet packs many sprites (or many animation frames of one sprite) into a single image, and the game draws one rectangle of it at a time. This lesson makes sprites without any image files: from text, from SVG data URLs and from drawing code. That keeps every game self-contained, and the same drawImage calls work unchanged with PNGs from an artist later.

Pixel art from text

The simplest sprite format is an array of strings, one character per pixel, plus a palette that maps characters to colors. It is easy to edit by hand and to keep in version control.

js · try it yourself
const HERO = [
  '..kkkk..',
  '.kssssk.',
  '.ksksks.',
  '.kssssk.',
  '..kbbk..',
  '.kbbbbk.',
  '..k..k..',
];
const PALETTE = { k: '#222', s: '#f5c28b', b: '#3f6fd8' };

// Count the pixels of each color: a quick check that the art is what you meant.
const counts = {};
for (const row of HERO) {
  for (const ch of row) {
    if (ch === '.') continue;                 // '.' is transparent
    counts[ch] = (counts[ch] ?? 0) + 1;
  }
}
console.log(`${HERO[0].length}x${HERO.length} sprite`);
console.log(counts);
console.log('colors used:', Object.keys(counts).map((c) => PALETTE[c]).join(' '));
8x7 sprite
{ k: 17, s: 11, b: 6 }
colors used: #222 #f5c28b #3f6fd8

To use it, bake it once into an offscreen canvas (one fillRect per pixel), then draw that canvas with drawImage every frame. Baking matters: drawing 56 tiny rectangles per sprite per frame is slow; one drawImage is fast.

Drawing a sprite with drawImage

drawImage has three forms:

Call Use
drawImage(img, x, y) Draw the whole image at its own size
drawImage(img, x, y, w, h) Draw it scaled to w × h
drawImage(img, sx, sy, sw, sh, x, y, w, h) Cut the rectangle sx, sy, sw, sh out of the image (one frame of a sheet) and draw it at x, y, w, h

img can be an <img>, another <canvas>, an OffscreenCanvas or an ImageBitmap. For pixel art drawn larger than its real size, set ctx.imageSmoothingEnabled = false, otherwise the browser blurs it.

html · try it yourself
<canvas width="480" height="270" style="width:100%;max-width:480px;image-rendering:pixelated;background:#000"></canvas>
<script>
const ctx = document.querySelector('canvas').getContext('2d');
const HERO = ['..kkkk..', '.kssssk.', '.ksksks.', '.kssssk.', '..kbbk..', '.kbbbbk.', '..k..k..'];
const PALETTE = { k: '#222', s: '#f5c28b', b: '#3f6fd8' };

function bake(rows, palette) {
  const c = document.createElement('canvas');
  c.width = rows[0].length;
  c.height = rows.length;
  const g = c.getContext('2d');
  rows.forEach((row, y) => [...row].forEach((ch, x) => {
    if (ch === '.') return;
    g.fillStyle = palette[ch];
    g.fillRect(x, y, 1, 1);
  }));
  return c;
}
const hero = bake(HERO, PALETTE);

ctx.fillStyle = '#6fa8dc';
ctx.fillRect(0, 0, 480, 270);
ctx.imageSmoothingEnabled = false;          // keep the pixels square
[1, 2, 4, 8, 16].forEach((s, i) => ctx.drawImage(hero, 20 + i * 70 + (i > 3 ? 10 : 0), 200 - 7 * s, 8 * s, 7 * s));

ctx.imageSmoothingEnabled = true;           // for comparison: a smoothed (blurry) 16x copy
ctx.drawImage(hero, 380, 40, 64, 56);
ctx.fillStyle = '#000';
ctx.font = '13px system-ui, sans-serif';
ctx.fillText('smoothing on', 380, 115);
</script>

Sprites as data URLs

An image does not have to come from a server. A data URL contains the file itself, for example a short SVG written inline. This is handy for icons and simple shapes, and it works offline and inside sandboxed frames:

js
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16">
  <polygon points="8,1 10,6 15,6 11,9 13,15 8,11 3,15 5,9 1,6 6,6" fill="#ffd54f" stroke="#a67c00"/>
</svg>`;
const star = new Image();
star.src = 'data:image/svg+xml,' + encodeURIComponent(svg);
star.onload = () => ctx.drawImage(star, 100, 100, 32, 32);   // wait for load before drawing

Any canvas can also be turned into a PNG data URL with canvas.toDataURL('image/png'). Real projects load PNG files exported from a pixel editor (see Tiled, LDtk & Aseprite); the drawing code stays the same.

Note: Images load asynchronously. Drawing an image before its load event draws nothing. Games load all assets first (with a progress bar for big games), then start the loop.

Sprite sheets and animation

A walk cycle is a few frames side by side in one sheet. To animate, pick the frame from the elapsed time: frame = Math.floor(time * fps) % frameCount. Testing that rule on its own shows how it behaves:

js · try it yourself
function frameAt(time, fps, frameCount) {
  return Math.floor(time * fps) % frameCount;
}
const times = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7];
console.log('8 fps:', times.map((t) => frameAt(t, 8, 4)).join(' '));
console.log('4 fps:', times.map((t) => frameAt(t, 4, 4)).join(' '));
// Source rectangle of a frame in a horizontal sheet of 16x16 frames:
const f = frameAt(0.45, 8, 4);
console.log(`frame ${f} -> sx=${f * 16}, sy=0, sw=16, sh=16`);
8 fps: 0 0 1 2 3 0 0 1
4 fps: 0 0 0 1 1 2 2 2
frame 3 -> sx=48, sy=0, sw=16, sh=16

Now a playable character with a procedurally drawn 4-frame sheet. It animates only while it walks, and mirrors itself with scale(-1, 1) when it walks left:

html · try it yourself
<style>
  html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
  canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set();   // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
  ctx.save();
  ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
  ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
  ctx.restore();
}
function run(update, draw, help = '') {
  const STEP = 1 / 60;
  let acc = 0, last = performance.now();
  requestAnimationFrame(function frame(now) {
    const dt = Math.min((now - last) / 1000, 0.1);
    last = now;
    if (active) {
      acc += dt;
      while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
      draw();
    } else if (!idleDrawn) {
      draw(); banner('Click to play', help); idleDrawn = true;
    }
    requestAnimationFrame(frame);
  });
}
// ---- end of play kit ----

// Build a 64x16 sheet: 4 walk frames of 16x16, drawn with code.
const FRAME = 16, FRAMES = 4;
const sheet = document.createElement('canvas');
sheet.width = FRAME * FRAMES;
sheet.height = FRAME;
const s = sheet.getContext('2d');
const legs = [[5, 9], [6, 8], [5, 9], [4, 10]];          // x of the two legs per frame
for (let f = 0; f < FRAMES; f++) {
  const ox = f * FRAME, bob = f % 2;                   // body bobs on frames 1 and 3
  s.fillStyle = '#f5c28b'; s.fillRect(ox + 5, 1 + bob, 6, 5);     // head
  s.fillStyle = '#222';    s.fillRect(ox + 9, 3 + bob, 1, 1);     // eye (faces right)
  s.fillStyle = '#3f6fd8'; s.fillRect(ox + 4, 6 + bob, 8, 5);     // body
  s.fillStyle = '#5d4037';
  s.fillRect(ox + legs[f][0], 11, 2, 5);                          // legs
  s.fillRect(ox + legs[f][1], 11, 2, 5);
}

const hero = { x: 220, y: 200, vx: 0, facing: 1, animTime: 0 };
const SCALE = 3;

function update(dt) {
  hero.vx = 0;
  if (keys.has('ArrowLeft') || keys.has('KeyA')) hero.vx = -90;
  if (keys.has('ArrowRight') || keys.has('KeyD')) hero.vx = 90;
  if (hero.vx !== 0) {
    hero.facing = Math.sign(hero.vx);
    hero.animTime += dt;                     // animate only while walking
  } else {
    hero.animTime = 0;                       // standing pose = frame 0
  }
  hero.x = Math.max(0, Math.min(W - FRAME * SCALE, hero.x + hero.vx * dt));
}

function draw() {
  ctx.fillStyle = '#87ceeb'; ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#4caf50'; ctx.fillRect(0, hero.y + FRAME * SCALE, W, H);
  // the sheet itself, for reference
  ctx.imageSmoothingEnabled = false;
  ctx.drawImage(sheet, 10, 10, sheet.width * 2, sheet.height * 2);
  const frame = Math.floor(hero.animTime * 8) % FRAMES;
  ctx.strokeStyle = '#d32f2f';
  ctx.strokeRect(10 + frame * FRAME * 2 + 0.5, 10.5, FRAME * 2 - 1, FRAME * 2 - 1);
  // the hero
  ctx.save();
  ctx.translate(Math.round(hero.x + (hero.facing < 0 ? FRAME * SCALE : 0)), hero.y);
  ctx.scale(hero.facing, 1);                 // mirror when facing left
  ctx.drawImage(sheet, frame * FRAME, 0, FRAME, FRAME, 0, 0, FRAME * SCALE, FRAME * SCALE);
  ctx.restore();
}

run(update, draw, 'Left/Right or A/D to walk');
</script>

The red box in the corner shows which frame of the sheet is being drawn. Change the 8 in hero.animTime * 8 to make the walk faster or slower.

Test yourself

Which drawImage call draws only the third 16×16 frame of a horizontal sprite sheet at (100, 50)?

  1. drawImage(sheet, 100, 50)
  2. drawImage(sheet, 32, 0, 16, 16, 100, 50, 16, 16)
  3. drawImage(sheet, 48, 0, 100, 50)
  4. drawImage(sheet, 100, 50, 32, 0)

Pixel-art sprites look blurry when drawn 4× larger. What fixes it?

  1. Use a bigger font
  2. ctx.imageSmoothingEnabled = false before drawImage
  3. Call ctx.scale(4, 4) twice
  4. Use strokeRect instead

Why bake a text-defined sprite into an offscreen canvas instead of calling fillRect per pixel every frame?

  1. Offscreen canvases have more colors
  2. One drawImage per frame is much cheaper than dozens of fillRect calls
  3. fillRect does not work in games
  4. To make the sprite transparent