Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 50 ยท Projects, Practice and Review

Project: A Mini Paint Program

Build a pixel paint program from scratch: Bresenham pencil, line, rectangle and circle tools, flood-fill bucket, color picker and undo, all in plain JavaScript.

The 2D chapters were full of algorithms that draw single pixels: Bresenham lines, the midpoint circle, flood fill. In this project you put them to work in something you can click on. You will build a small paint program with a pencil, shape tools, a paint bucket, a color picker and an undo button, and every pixel it draws comes from your own code, not from the browser's lineTo or fill.

The project is also a lesson in program design. A paint program is mostly about state: the pixel buffer, the current tool, a preview while you drag, and a history to go back to. Getting that state right is more important than any single algorithm.

The design

The picture is a plain array of 32-bit integers, one per pixel, just like the frame buffer from Pixels, Resolution and the Framebuffer. We use a small 160 by 120 buffer and let the browser scale the canvas up with image-rendering: pixelated, so every logical pixel is a chunky square and you can see exactly what the algorithms do.

flowchart TD
  A["Pointer events<br/>down, move, up"] --> B{"Which tool?"}
  B -->|pencil, eraser| C["Bresenham line<br/>from last point to this point"]
  B -->|line, rectangle, circle| D["Restore the saved base picture,<br/>draw the shape as a preview"]
  B -->|bucket| E["Flood fill from the clicked pixel"]
  C --> F["Pixel buffer"]
  D --> F
  E --> F
  F --> G["putImageData to the canvas"]
  H["Undo stack<br/>copies of the buffer"] -.-> F

All tools only write to one pixel buffer; the canvas is just a view of it.

Pencil: connecting the dots with Bresenham

Pointer events arrive at discrete moments. If you move the mouse fast, two consecutive events can be 30 pixels apart, and plotting only the event positions leaves a trail of dots. The fix is to draw a line from the previous position to the current one. Bresenham's algorithm (Bresenham's Line Algorithm) in its all-octant integer form is perfect for this: no division, no floating point, no gaps.

TEXT
dx = |x1 - x0|, sx = x0 < x1 ? 1 : -1
dy = -|y1 - y0|, sy = y0 < y1 ? 1 : -1
err = dx + dy
loop:
    plot(x0, y0)
    if x0 == x1 and y0 == y1: stop
    e2 = 2 * err
    if e2 >= dy: err += dy, x0 += sx
    if e2 <= dx: err += dx, y0 += sy

The eraser is the same tool with the background color.

Shapes: preview while you drag

A rectangle or circle should follow the pointer while the button is down, and only the final shape should stay. The classic trick: when the button goes down, take a copy of the buffer (the base picture). On every move, copy the base back and draw the shape for the current pointer position. On release, simply stop; the last preview is already in the buffer. The rectangle is four Bresenham lines; the circle uses the midpoint circle algorithm with the distance from the centre to the pointer as the radius.

The bucket: flood fill with an explicit stack

The paint bucket replaces a connected region of one color with another. We use the 4-connected, stack-based version from Flood Fill and Boundary Fill, because the recursive version overflows the call stack on a large empty canvas. Two details matter: if the clicked pixel already has the new color, return immediately (otherwise you loop forever), and push a pixel only if it still has the target color.

Undo: snapshots

The simplest correct undo is to copy the whole buffer before every action and push it on a stack. A 160 by 120 buffer is only 76 KB, so even 50 snapshots cost less than 4 MB. Real editors store differences instead, but the snapshot approach has no bugs to hide in.

A brush size

All tools plot through one function, stamp(x, y), which draws a square of the chosen size centred on the pixel. Since every tool goes through it, one setting changes them all.

The program

Pick a tool, pick a color from the swatches or the color input, and draw. Try the bucket on the inside of a rectangle or circle, then undo it. Try the bucket on a shape that has a one-pixel gap in its outline and watch the color leak out: that is the "leaking fill" problem in action.

A mini paint program

The same engine, without a screen

Because all the algorithms only touch an array, you can run them anywhere, including in a console. The second example makes a 36 by 14 text canvas, uses the same line, circle and flood fill, and shows the undo stack at work. It is also a model for how you would unit-test a paint program: compare arrays, not screenshots.

JS Paint tools on a text canvas

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

No output.

Notice that the second bucket click fills only the part of the circle that the diagonal line leaves connected to the click point. The line is a wall for a 4-connected fill, exactly as the rectangle's outline is.

Where to go from here

  • Brush shapes and a spray can. Stamp a circle or random dots inside a radius.
  • Eight-connected fill and a tolerance. Fill pixels whose color is within a distance of the target, as real editors do.
  • Scanline fill. Replace the pixel-by-pixel stack with spans, as in Scanline Polygon Filling-style loops. It is several times faster on big areas.
  • Redo. Keep a second stack: undo moves the current picture to it, a new action clears it.
  • Antialiased shapes. Switch the line tool to Wu's algorithm from Aliasing and Antialiasing with an alpha blend.
  • Save as image. canvas.toDataURL() gives you a PNG (the sandbox of this page blocks downloads, but your own site will not).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the pencil draw a Bresenham line between consecutive pointer positions?

    Two successive events can be many pixels apart. Connecting them with a line leaves a continuous stroke instead of separate dots.
  2. 2. How does the rectangle tool show a preview without leaving a trail of old rectangles?

    Restoring the saved base picture before every redraw removes the previous preview, so only the current shape is visible.
  3. 3. What must the bucket tool check before it starts filling?

    If the target color equals the fill color, the fill would never mark pixels as different from the target and would loop forever.
  4. 4. Why is a stack-based fill preferred to a recursive one here?

    Recursive fill uses one call frame per pending pixel. An explicit array on the heap can grow far larger than the call stack.
  5. 5. Which approach gives the simplest correct undo?

    Snapshots need no knowledge of how the action changed the picture, so they cannot get out of sync. The cost is memory, which is small for a small canvas.

Summary

  • A paint program is a pixel buffer plus tools that write to it; the canvas only displays the buffer.
  • The pencil connects pointer events with Bresenham lines; shapes use a saved base picture to draw a live preview.
  • The midpoint circle and a stack-based 4-connected flood fill give you the circle and bucket tools.
  • All tools draw through one stamp function, so brush size and color work everywhere.
  • Undo is a stack of buffer snapshots; leaks in the bucket come from gaps in outlines.

Next, trade pixels for light rays in Project: A Ray-Traced Scene.