Interactive Vision From Zero · Episode 01

Your Webcam Is an Input Device

Your Webcam Is an Input Device is Episode 01 of Interactive Vision From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 01 · Interactive Vision From Zero

You think of your webcam as a thing that records you. It is not. A webcam is an input device — a keyboard that types in pixels. Every frame it hands your browser is the same kind of object as a mouse position or a key press: just numbers, arriving sixty times a second, waiting for you to read them and react. The moment that clicks, the camera stops being a mirror and becomes a controller.

By the end of this page you'll have turned a live video frame into edge-glow neon, flickering ASCII, and a CRT scanline trip — and you'll understand that every one of those effects is the same trivial move: read a Uint8ClampedArray, rewrite some bytes, write it back. A 640×480 frame is 921,600 numbers (that's 640 · 480 · 3 RGB channels). That's the realization this whole series is built on: a frame is an array. Hold that thought, because next episode a hand collapses into just 21 of them. The demo below is alive right now with no camera at all — it's processing a synthetic test feed. Press "use my camera" whenever you want to feed it your face instead.

0 fps
synthetic feed — no camera in use
🔒 on-device · nothing uploaded
Canvas 2D · getImageData
The source frame, drawn straight to the canvas. Synthetic until you opt in.

What you're looking at

There is one source of pixels and a pipeline of effects that read from it. By default the source is a synthetic video feed — drifting color bars, a roaming radial blob, a moving grid, and a live frame counter, all drawn to an offscreen canvas every frame. It exists for one reason: the pipeline always needs a frame to chew on. No camera, no permissions prompt, no network — but the machine still runs so you can read the code and watch the effects work. When you click use my camera, the exact same pipeline switches its source to a real <video> element. Nothing downstream changes. That is the whole trick of this series: build against a synthetic driver, then swap in reality through the identical code path.

Pick a stage from the dropdown to change the effect. The intensity slider means something different per stage (glow strength, ASCII cell size, scanline depth). Mirror flips the image like a selfie camera and is on by default — more on why below. The green number top-left is your frame rate; the badge bottom-left names the two APIs doing all the work: drawImage to grab the frame and getImageData to read its bytes.

Stage 1 — Raw feed

The source frame, drawn straight to the canvas with a single drawImage. Nothing is read, nothing is rewritten — this is the baseline. If you're on the synthetic feed you'll see the test pattern animating; if you opt into the camera, it's you, un-mirrored, which means text behind you reads correctly and your movements feel backwards. That backwardness is exactly what Stage 2 fixes.

Stage 2 — Mirror

A webcam points at you, so raw camera video is a true image: raise your right hand and it appears on the left side of the frame, the way someone facing you would see it. Humans hate that, because we grew up with mirrors. The fix is one line — flip the X axis before drawing — and suddenly the feed behaves like a mirror: raise your right hand, the on-screen hand on your right goes up. We do it with ctx.scale(-1, 1). This selfie flip matters far beyond cosmetics: in the next episode, when a fingertip becomes an (x, y) coordinate, a forgotten mirror is the number-one reason the on-screen hand drifts the wrong way. Decide your convention now.

Stage 3 — Edge glow

The first real pixel kernel. For each pixel we compare its brightness to its neighbors — a tiny Sobel gradient — and where brightness changes sharply (an edge), we paint neon; everywhere flat, we paint black. The result is your silhouette and features traced in glowing outline on a dark field. The intensity slider scales the glow. This is the same family of operation that, scaled up, becomes feature detection — the ancestor of "where is the hand."

Stage 4 — ASCII

Chop the frame into a grid of cells. Average the brightness inside each cell, map that single number to a character from a ramp (dark→light: " .:-=+*#%@"), and stamp it with fillText. The image becomes text. Here intensity controls cell size: slide it down for fine, dense type; up for chunky blocks. It's a vivid demonstration that an image is just brightness you can re-encode into any alphabet — pixels in, characters out.

Stage 5 — CRT / scanlines

Three cheap tricks that read as "old monitor": darken every other row (scanlines), nudge the red and blue channels a pixel apart (chromatic aberration / RGB shift), and fade the corners (vignette). Intensity deepens the scanlines and the color split. None of it is physically simulated — it's just arithmetic on bytes — but your brain instantly reads "TV." Proof that convincing image effects are often a few arithmetic ops per pixel, nothing more.

Stage 6 — It's just an array

The payoff stage, and the thesis of the episode. The frame is shown plainly, but move your cursor over it and a readout reports the exact RGBA bytes living under that point — four integers in 0…255. A banner reminds you that the image you're looking at is 921,600 numbers for a 640×480 frame. There is nothing magic in a video frame: it is a flat list of bytes you can address and rewrite one at a time. And here's the foreshadow that powers everything after this page: next episode we throw almost all of those numbers away. A whole hand — every pose, every gesture — collapses into 21 points. The frame is the raw material; the landmarks are the meaning we extract from it.

How the code works

Everything hangs off one idea: a source canvas that always holds the current frame, whether that frame came from the synthetic generator or a real camera. Effects never touch the camera directly — they read the source canvas. Swapping inputs is therefore just changing what we draw into that canvas.

1 · Getting a real camera (the lazy, safe way)

The camera is opt-in and wrapped in try/catch so a camera-less page never errors. getUserMedia only works in a secure context — https:// or localhost. Open this file as file:// and the camera silently fails (the synthetic feed keeps running, so the demo survives). The <video> must be muted + playsInline or the browser blocks autoplay:

let usingCamera = false, video = null;

async function enableCamera() {
  try {
    // secure context only: https:// or localhost. file:// silently fails.
    const stream = await navigator.mediaDevices.getUserMedia({
      video: { facingMode: 'user' }       // the front / selfie camera
    });
    video = document.createElement('video');
    video.srcObject  = stream;
    video.muted      = true;             // muted + playsInline →
    video.playsInline = true;            // browser allows autoplay
    video.autoplay   = true;
    await video.play();              // must call play() explicitly
    usingCamera = true;
    setStatus('camera live · on-device, nothing uploaded');
  } catch (err) {
    // denied, no device, or insecure context — keep the synthetic feed
    setStatus('camera unavailable — staying on synthetic feed (' + err.name + ')');
    usingCamera = false;
  }
}

2 · The per-frame loop: draw → read → rewrite → write

Every frame we draw the current source (camera or synthetic) into the source canvas, pull its bytes with getImageData, mutate them, and push them back with putImageData. The performance secret: getImageData is the slow part, so we process at a reduced resolution — a small source canvas scaled up to the display — not at full screen res:

// src = small offscreen canvas (e.g. 320×200). We process here, then upscale.
function tick(t) {
  // 1 · put the latest frame into the source canvas
  if (usingCamera && video && video.readyState >= 2) {
    drawFrame(srcCtx, video);          // real camera frame
  } else {
    drawSynthetic(srcCtx, t);          // procedural test feed
  }

  // 2 · read the raw bytes — one flat Uint8ClampedArray, RGBA per pixel
  const img = srcCtx.getImageData(0, 0, src.width, src.height);
  const px = img.data;                   // length = width · height · 4

  // 3 · rewrite the bytes for the chosen effect
  applyEffect(px, src.width, src.height, stage, intensity);

  // 4 · write them back, then blit the small canvas onto the big one
  srcCtx.putImageData(img, 0, 0);
  ctx.drawImage(src, 0, 0, view.width, view.height);

  requestAnimationFrame(tick);
}

3 · One pixel kernel: ASCII from average luminance

Per cell, sum brightness, divide to get an average, map it onto a character ramp. The 0.299 / 0.587 / 0.114 weights are standard luminance (we see green as brightest, blue as dimmest). This is the entire ASCII effect:

const RAMP = ' .:-=+*#%@';             // dark → light

function asciiCell(px, w, x0, y0, cell) {
  let sum = 0, n = 0;
  for (let y = y0; y < y0 + cell; y++) {
    for (let x = x0; x < x0 + cell; x++) {
      const i = (y * w + x) * 4;       // 4 bytes/pixel: R,G,B,A
      // luminance: weight green up, blue down — how the eye sees
      sum += 0.299*px[i] + 0.587*px[i+1] + 0.114*px[i+2];
      n++;
    }
  }
  const lum = sum / n / 255;            // 0…1 average brightness
  return RAMP[Math.min(RAMP.length - 1, (lum * RAMP.length) | 0)];
}

4 · The mirror is one transform

To flip horizontally, translate to the right edge and scale X by -1 before drawing. Everything drawn afterward is mirrored; wrap it in save/restore so the flip doesn't leak:

function drawFrame(c, source) {
  c.save();
  if (mirror) {
    c.translate(c.canvas.width, 0);  // move origin to the right edge
    c.scale(-1, 1);                  // flip the X axis
  }
  c.drawImage(source, 0, 0, c.canvas.width, c.canvas.height);
  c.restore();                          // flip stops here
}

Common pitfalls

  • Camera does nothing and there's no error. You're on file:// or plain http://. getUserMedia requires a secure context — serve over https:// or localhost. (This is why the demo falls back to a synthetic feed instead of crashing.)
  • Black video that never plays. Browsers block autoplay of media with sound. The <video> needs muted + playsInline, and you must call video.play() yourself (ideally from a user click, which the camera button gives you for free).
  • The whole thing is sluggish. getImageData / putImageData are the expensive calls, and they scale with pixel count. Process on a small offscreen canvas (320×200 is plenty) and upscale with one drawImage. Never run a per-pixel loop at full display resolution.
  • "Tainted canvas" / SecurityError on read. The moment you draw a cross-origin image without CORS into a canvas, the browser refuses to let you call getImageData. Camera and same-origin assets are fine; if you pull in a remote image, serve it with crossorigin="anonymous" and proper CORS headers.
  • The image goes the wrong way. Mirror confusion. Decide on the selfie flip (scale(-1, 1)) once and apply it consistently — and remember it again next episode when you map landmark coordinates to the screen.

Exercises

  1. Posterize / threshold. Add a seventh effect that snaps each channel to a few levels: v = Math.round(v / step) * step with step from the intensity slider. At step = 255 you get a stark two-tone threshold; in between, a poster look. One line in the per-pixel loop.
  2. Measure the cost of reading pixels. Sample only every Nth pixel in your kernel (skip the loop by N in both axes) and watch the fps counter climb as N grows. You'll feel, in numbers, why "process at lower res" is the rule — and see the quality you trade for it.
  3. Tint by the frame's average color. Sum every pixel's R, G, B, divide by the count to get the mean color of the whole frame, and multiply it back over the image (or just fill a corner swatch with it). You've computed a one-value summary of 921,600 numbers — a baby step toward extracting meaning from a frame, which is exactly what landmarks do.

What's next

Episode 02 — Hello, Hand Landmarks. We stop rewriting all 921,600 numbers and start throwing them away. MediaPipe's Hand Landmarker reads the frame and hands back just 21 points — {x, y, z} each — and suddenly the camera isn't a stream of pixels, it's a stream of coordinates. The frame was the raw material; the hand is the data. Same synthetic-then-camera pattern, same downstream code — but now we're tracking.