Skip to content
Tutorials Center
My learning

Topics

Lesson 87 of 96 ยท Projects

Project: Pixel Art Maker

Build a pixel art editor in TypeScript - an immutable grid with a typed palette, drawing tools (pencil, line, flood fill), generic undo and redo, SVG and JSON export, and canvas-shaped rendering.

A pixel art editor is a grid of colored squares and a few tools to paint them. It is a lovely project for practicing state modeling: the whole picture is data, every tool is a function from one picture to the next, and undo and redo become almost free once you treat the picture as immutable.

In three stages you will build the grid and tools, add export and import with validation, and finally draw to a canvas-shaped interface and translate mouse positions into grid cells. As in the other projects, the browser parts are written against small interfaces so everything runs here, and you only need a few lines to connect real elements.

Stage 1: the grid, the palette and the tools

First, the data. A palette defined with as const gives us a literal union of colors; a cell is either a palette color or null (empty). The grid stores cells in one flat array and is never modified in place: each tool returns a new grid.

TypeScript Stage 1: typed grid, pencil, line and flood fill

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The type of Color comes from the palette array itself, so the list of allowed colors and the type can never disagree: add a color to PALETTE and the type grows. The last (commented) line shows the payoff, since only palette colors compile. Everything is readonly: setCell slices the array before changing it, and returning g itself when nothing changed lets UI code skip a redraw with a simple === check.

Stage 2: undo, redo and export

Because each tool returns a new grid, history is just a list of grids. A tiny generic class handles it; nothing in it knows about pixels.

TypeScript Stage 2: a generic History, SVG export and validated import

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

History<T> shows why generics pay off. It knows nothing about grids, so you can reuse it for a text editor or a form. Notice that undo is cheap because grids are immutable: the history stores references, and unchanged data is shared rather than copied (for big pictures you could store only the changed cells).

Import is where types stop protecting you: JSON arrives as unknown, so importJson checks every piece before it returns a Grid, using the isColor type guard to narrow each cell. This is the same idea as in Validating Data with Zod, written by hand for a small shape.

Stage 3: drawing on a canvas-shaped surface

The last piece turns grid cells into pixels on a canvas, and mouse positions back into grid cells. We describe the canvas with just the methods we call.

TypeScript Stage 3: rendering and pointer-to-cell mapping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The scaling step is the classic bug in canvas editors: a canvas that is 48 pixels wide may be displayed 96 pixels wide with CSS, and the browser reports pointer coordinates in displayed pixels. Dividing by the displayed size and multiplying by the canvas size fixes it.

In a browser, real elements fit these shapes. A CanvasRenderingContext2D already has fillStyle, fillRect and clearRect, and canvas.getBoundingClientRect() returns a DOMRect with left, top, width and height:

TypeScript
const canvas = document.querySelector<HTMLCanvasElement>('#pixels');
const ctx = canvas?.getContext('2d');

if (canvas && ctx) {
  let drawing = false;

  canvas.addEventListener('pointerdown', (event) => {
    drawing = true;
    paintAt(event);
  });
  canvas.addEventListener('pointermove', (event) => {
    if (drawing) paintAt(event);
  });
  window.addEventListener('pointerup', () => { drawing = false; });

  function paintAt(event: PointerEvent): void {
    const cell = cellAt(history.value, canvas.getBoundingClientRect(), event.clientX, event.clientY);
    if (cell) {
      history.push(setCell(history.value, cell, currentColor));
      render(ctx, history.value);
    }
  }
}

Pointer events (rather than mouse events) make the editor work with touch and pens too. For crisp pixels, add image-rendering: pixelated in CSS.

Ideas to extend it

  • Add a mirror tool that paints two cells at once (reflect x across the center).
  • Add an eraser (it is setCell with null) and a shape tool for rectangles, built from lineCells.
  • Save pictures in localStorage through exportJson, and validate them on load with importJson.
  • Let users add their own colors by turning Color into a string and validating hex codes with a template literal type like `#${string}`.
  • Export a PNG with canvas.toBlob.
  • Animate: keep an array of grids as frames and play them with a timer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does type Color = (typeof PALETTE)[number] work with as const?

    as const keeps each value as a literal type, and indexing the tuple with number produces their union.
  2. 2. Why does setCell return the original grid when nothing changes?

    With immutable data, an unchanged result can be recognized by reference equality, so redraws and history entries can be skipped.
  3. 3. Why is History<T> generic?

    Undo and redo only move values between stacks, so the element type can be a parameter.
  4. 4. What type does JSON.parse return, and what must importJson do with it?

    Data from outside the program is untrusted, so each part is checked and narrowed before use.
  5. 5. Why does cellAt scale pointer coordinates?

    Pointer positions are in displayed pixels, while cells are measured in canvas pixels.

Summary

  • Derive a literal Color union from an as const palette so values and type stay in sync.
  • Keep the picture immutable: every tool returns a new grid, or the same grid when nothing changes.
  • Pencil, line (Bresenham) and bucket (flood fill) are small pure functions on Grid.
  • A generic History<T> gives undo and redo for any immutable state.
  • Treat imported JSON as untrusted: validate each field and use type guards to narrow.
  • Describe the canvas with a tiny interface and scale pointer coordinates to canvas pixels.

Next: Project: Typed Quiz App