Skip to content
Tutorials Center
My learning

Topics

Lesson 147 of 156 ยท Projects

Project: Stack Visualizer and Simple Image Editor

Build an animated stack visualizer to see push and pop happen, then a non-destructive canvas image editor with brightness, contrast, filters, flip and rotate.

Some ideas only click when you can see them. A stack is easy to define (last in, first out) but much easier to understand when you watch boxes land on top of each other and leave again. In the first half of this project you will build a stack visualizer that animates every operation. In the second half you will build a simple image editor that edits pixels on a <canvas>: brightness, contrast, colour filters, flip and rotate, with a Reset button that works because the editor never destroys the original.

Both projects teach the same architecture lesson. Keep a clean model (the stack, or the original pixels plus a list of settings) that knows nothing about the screen, and write a view that draws it. Then animation and interactivity become small, separate jobs.

You will use ideas from Data Structures in JavaScript, Timers and Canvas Drawing from JavaScript.

Part 1: The stack visualizer

The model: a stack with a limit

A stack allows two main operations at one end only: push adds to the top, pop removes from the top. A peek looks at the top without removing it. Giving the stack a maximum size lets you also demonstrate overflow (pushing onto a full stack) and underflow (popping an empty one), which real programs must handle.

The model below is a class that returns results and throws nothing, so the interface can show friendly messages. It has no idea that a screen exists.

JS Stack model and an everyday use

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

No output.

The #items field is private (see Private and Static Members), so outside code can only change the stack through push and pop. That is exactly what makes a stack a stack.

The view: boxes that land and leave

The page shows the stack as a column of boxes with the newest at the top. The view follows two rules:

  1. render() draws the stack from the model. When you push, only the new box gets an "enter" class (a CSS animation that drops it from above). When you pop, the top box gets a "leave" class, and the model is updated after the animation, so the box visibly lifts off before it disappears.
  2. Input is locked during an animation so quick clicks can't desynchronise the screen from the model.

The messages go into a role="status" line, so screen reader users hear "Pushed 7" or "Underflow" too. The animations are turned off for people who ask for reduced motion.

Stack visualizer

Push values until you see Overflow, then pop them all to reach Underflow. The numbers come out in the reverse of the order they went in.

A few things worth noticing in the code:

  • Animate first, then change the model. pop() adds the leave class and removes the item from the array only after the animation's time has passed. Doing it in the opposite order would make the box vanish before it can move.
  • The busy flag ignores clicks while the lift-off plays. For larger visualizers (sorting, trees) you would put the steps in a queue and play them one after another, using async/await with a small sleep(ms) helper.
  • A timer is used instead of animationend, because when reduced motion turns animations off, animationend never fires and the interface would freeze waiting for it.
  • Newest-first order. The array has the top at the end, but the screen shows the top first (.reverse()), and justify-content: flex-end keeps the pile at the bottom.

Part 2: A simple image editor

Edits as pure pixel maths

An image on a canvas is a long array of numbers. ctx.getImageData(0, 0, w, h).data is a Uint8ClampedArray with four numbers per pixel: red, green, blue and alpha, each 0 to 255. "Clamped" means that assigning 300 stores 255 and -20 stores 0, so you never have to check the range yourself.

Every editing operation is a small formula applied to each pixel:

Edit Formula for each colour value v
Brightness b (-100 to 100) v + b * 2.55
Contrast c (-100 to 100) factor * (v - 128) + 128, with factor = 259(c + 255) / (255(259 - c))
Saturation s (-100 to 100) gray + (v - gray) * (1 + s / 100), where gray = 0.299R + 0.587G + 0.114B
Grayscale set R, G and B to gray
Invert 255 - v
Sepia a fixed mix of R, G, B (shown below)

The weights in gray reflect how bright our eyes see each colour: green counts most and blue least. You can try these on three pixels in the console before touching a canvas.

JS Pixel maths on a tiny image

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

No output.

Look at how the red pixel behaves: brightness pushes 255 to the 255 limit (clamped), and saturate(-100) turns all three pixels into greys.

The editor: original plus settings

The golden rule of a non-destructive editor: never edit the original pixels. Keep them, plus an object of settings. On every change, copy the original, apply the settings in a fixed order and draw the result. Because the pipeline always starts from the untouched copy, sliders can move back and forth without quality loss, and Reset just restores the default settings.

Geometry (flip and rotate) is easier with canvas transforms than with pixel loops: draw the source into a working canvas with translate, scale and rotate, then read the pixels from that canvas for the colour edits.

Image editor with sliders, filters, flip and rotate

Drag Brightness left and right: it never degrades, because each frame starts from original. Toggle Sepia and Invert together, rotate, flip, then press Reset and watch the picture return to exactly how it began.

Design notes:

  • Settings are a plain object, and render() is the only function that touches the canvas. Adding a new filter means one field in defaults, one control and one line in apply().
  • Order matters. Geometry happens first, then brightness, contrast, saturation, sepia and invert in a fixed order. A different order gives different pictures, because the formulas do not commute.
  • willReadFrequently: true tells the browser you will call getImageData() often, so it keeps the pixels in memory instead of on the GPU, which is faster for this pattern.
  • Speed. This loops over every pixel, which is fast for pictures of a few megapixels. For larger images or heavier filters, run the loop in a Web Worker or use WebGL.
  • Loading real pictures: replace the generated original with await createImageBitmap(file). Remember that images from another website without CORS permission taint the canvas, and getImageData() then throws a SecurityError.

Ideas to extend it

  • Undo and redo for the stack visualizer's cousin: keep a stack of settings objects and pop one on Undo. That is the real-world use of the data structure you just animated.
  • Visualize a queue with the same view code: enqueue at the back, dequeue from the front.
  • Blur and sharpen with a convolution kernel (a 3 by 3 grid of weights applied around each pixel).
  • Crop tool that drags a rectangle and uses the nine-argument form of drawImage().
  • Histogram: count how many pixels have each brightness and draw the bars on a second canvas.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In the stack visualizer, why does pop() remove the item from the array only after the animation time?

    The screen is drawn from the model. If the model changes first and render() runs, the box vanishes before the animation can play.
  2. 2. What is special about Uint8ClampedArray, the type used by getImageData().data?

    Assigning 300 stores 255 and assigning -20 stores 0, so pixel code doesn't need explicit range checks.
  3. 3. Why does the editor keep an untouched original and a settings object?

    Filters applied one on top of another accumulate rounding and clipping errors. Recomputing from the original every time avoids that.
  4. 4. Why is a stack's push on a full stack reported as 'overflow'?

    A bounded stack refuses to grow past its capacity. Real call stacks overflow the same way when recursion goes too deep.

Summary

  • A stack is last in, first out: push, pop and peek work on the top only; a limit adds overflow and underflow cases to handle.
  • Keep the model (the stack, or original pixels plus settings) free of screen code and draw it with a render() function.
  • To animate a removal, play the animation first and change the model after; lock input while an animation runs and prefer a timer to animationend when reduced motion may disable animations.
  • Canvas pixels are a Uint8ClampedArray of R, G, B, A values; each filter is a small formula over every pixel.
  • A non-destructive editor re-applies its settings to an untouched original on every change, so Reset and slider moves are free of quality loss.
  • Use canvas transforms for flip and rotate, willReadFrequently for repeated pixel reads, and workers or WebGL for heavy images.

Next: Dark Mode, Mobile Nav, Expanding Cards, Accordion or on to Data Structures in JavaScript.