Real-Time & Streaming From Zero · Episode 08

A Shared Live Space

A Shared Live Space is Episode 08 of Real-Time & Streaming From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

← real-time-streaming-from-zero Episode 08 · Finale
Episode 08 · Real-Time & Streaming From Zero

This is the one we've been building toward. Over seven episodes you turned a blank canvas into a live MediaStream, opened the camera, shook hands with a peer over WebRTC, pushed bytes down a data channel, synced cursors across tabs, smoothed them with netcode, and composited a broadcast. Today we glue all of it into a single thing you can walk into: a tiny multiplayer room. Synced cursors. Named, colored avatars. A shared whiteboard everyone draws on. Live video tiles. A presence list that fills and empties as people come and go. And it runs with no backend at all.

Here's the magic trick that makes it feel real: the demo is fully alive on its own. Open it solo and you'll find the room already populated — friendly bots drift their cursors around and scribble on the whiteboard, and a couple of video tiles glow with synthetic motion. Then do the thing that turns a toy into a capstone: open this exact page in a second browser tab. A new avatar appears in both. Your real cursor shows up over there. Draw a line and it lands on the other tab's whiteboard. No server saw a single byte. Let's assemble the room one layer at a time.

0 fps
synthetic · serverless
1 in room
Everything live. Open a 2nd tab to genuinely join.

In the room: drag on the canvas to draw on the shared whiteboard; your cursor and strokes broadcast to every open tab. Participants:

    What you're looking at

    One <canvas> is the room floor. We draw, in order: the persistent whiteboard strokes, then everyone's avatar puck at their cursor position, then a soft nameplate. Off to the side, a stack of <video> elements are the webcam tiles. Nothing here is faked-looking-but-static: the bots are on real Lissajous paths and emit the same messages a real peer would, so the bot code and the network code share one render path. That's the whole design philosophy of this series in one sentence — the synthetic source and the real source are interchangeable, so the demo is never a dead screen and the upgrade never needs special-casing.

    The six stages assemble the room from nothing:

    • 1 · The room. Just presence — you plus the synthetic bots, each an avatar with a name and a color. The participant list below fills in.
    • 2 · + Cursors. Everyone's cursor moves live, broadcast over BroadcastChannel exactly as in Episode 05. Your real mouse drives your puck.
    • 3 · + Whiteboard. Drag to draw. Each stroke segment is broadcast and replayed, so every tab converges on the same canvas.
    • 4 · + Presence. Join/leave events, names, colors, and a roster that prunes anyone who's gone quiet for ~4 seconds.
    • 5 · + Video tiles. A loopback self-view tile (real WebRTC, you're both ends) plus synthetic-source peer tiles.
    • 6 · The full room. All of it, live. Now open a second tab.

    The room state: one tagged-message protocol

    A "room" sounds like a lot, but it's really just a handful of message types flowing over a single BroadcastChannel. Every participant — you, a bot, a peer in another tab — speaks the same little protocol. We tag each message with a kind so one onmessage handler can route it. Three kinds carry the whole room: cursor (where someone's pointer is), stroke (a line segment drawn on the board), and presence (I'm here / I'm leaving, plus my name and color).

    // One channel, one tagged protocol. Same-origin, cross-tab, zero server.
    const room = new BroadcastChannel('streaming-room-08');
    const me = {
      id:    Math.random().toString(36).slice(2),
      name:  'You',
      color: `hsl(${(Math.random()*360)|0},75%,62%)`,
      x: 0.5, y: 0.5,                 // cursor in 0..1 room space (resolution-independent)
    };
    const peers = new Map();              // id → { name, color, x, y, last }
    
    function send(kind, data) {        // every outgoing message is tagged + stamped
      try { room.postMessage({ kind, from: me.id, t: Date.now(), ...data }); }
      catch (e) { /* channel closed / unavailable — never break the room */ }
    }
    
    room.onmessage = (e) => {
      const m = e.data; if (!m || m.from === me.id) return;   // ignore our own echo
      if (m.kind === 'cursor')   upsertPeer(m.from, { x: m.x, y: m.y });
      if (m.kind === 'stroke')   drawStroke(m.seg, m.color);   // replay onto the board
      if (m.kind === 'presence') {
        if (m.bye) peers.delete(m.from);
        else      upsertPeer(m.from, { name: m.name, color: m.color });
        if (m.hello) send('presence', { name: me.name, color: me.color }); // answer a newcomer
      }
    };
    
    function upsertPeer(id, patch) {
      const prev = peers.get(id) || {};
      peers.set(id, { ...prev, ...patch, last: performance.now() });   // last = liveness clock
    }

    That's the spine. Notice three deliberate choices. Cursor positions are stored in 0..1 room space, not pixels — so a tab at a different size still places your puck correctly (you'd be amazed how many multiplayer toys break on this). The last timestamp on every peer is our liveness clock for pruning. And every send() is wrapped in try/catch: if the channel is ever unavailable, the room keeps rendering its synthetic state instead of throwing. The baseline must never break — that's the rule from the authoring brief, and it's why this demo is alive even with networking switched off.

    Keeping the room alive: synthetic bots

    If the room only showed real peers, a solo visitor would see an empty void and assume it's broken. So we populate it with bots. The trick that keeps the code honest: a bot is just another entry in the same peers map, moved by a little parametric path, and it occasionally draws on the whiteboard through the exact same drawStroke the network uses. There's no "bot renderer" and "peer renderer" — there's one renderer, and bots are first-class citizens of it.

    // Bots: animated cursors on Lissajous paths that also scribble on the board.
    function makeBots(n) {
      const names = ['Ada', 'Lin', 'Rio', 'Mei', 'Kai', 'Sol'];
      return Array.from({ length: n }, (_, i) => ({
        id:    'bot-' + i,
        name:  names[i % names.length],
        color: `hsl(${(i * 57 + 20) % 360},72%,60%)`,
        ax: 0.6 + i * 0.5, ay: 0.9 + i * 0.4,        // Lissajous frequencies
        ph: i * 1.7,                                  // phase offset so they spread out
        nextDraw: 1 + Math.random() * 2,             // seconds until next scribble
        px: null, py: null,                            // previous point, for stroke segments
      }));
    }
    
    function tickBots(bots, dt, t) {
      for (const b of bots) {
        const x = 0.5 + 0.4 * Math.sin(t * b.ax + b.ph);   // 0..1 room space
        const y = 0.5 + 0.36 * Math.cos(t * b.ay + b.ph * 1.3);
        upsertPeer(b.id, { name: b.name, color: b.color, x, y });  // same map as real peers
        b.nextDraw -= dt;
        if (b.nextDraw <= 0 && b.px != null) {            // emit a real stroke segment
          const seg = { x0: b.px, y0: b.py, x1: x, y1: y };
          drawStroke(seg, b.color);                       // draw locally…
          // (bots stay local; real peers' strokes arrive over the channel)
        }
        if (b.nextDraw <= 0) b.nextDraw = 0.4 + Math.random() * 1.6;
        b.px = x; b.py = y;
      }
    }

    Drag the bots slider in the demo from 0 to 6 and watch the room breathe. At zero, you're alone (great for proving your real cursor/stroke code without distraction). At six, it looks like a busy Figma file at 2pm. Because bots emit the same shapes as the network, you can develop the entire room offline and trust it'll behave the moment a second tab joins.

    The shared whiteboard: broadcast segments, replay them

    A collaborative whiteboard sounds hard and is almost embarrassingly simple once you have the protocol. The insight: don't sync the picture, sync the brushstrokes. When you drag, you generate a stream of tiny line segments — "from this point to that point." You draw each segment on your own canvas and broadcast it. When a segment arrives from someone else, you run the identical draw call. Everyone applies the same ordered list of segments, so everyone's canvas converges. This is the seed of a CRDT — a conflict-free replicated data type — which is exactly where Season 2 picks up.

    // The board is its own offscreen canvas so cursors/avatars can redraw without erasing it.
    const board = document.createElement('canvas');
    const bctx  = board.getContext('2d');
    const history = [];                                  // keep segments for late-join snapshots + redraw
    
    function drawStroke(seg, color) {                     // the ONE draw used by me, bots, AND peers
      bctx.strokeStyle = color; bctx.lineWidth = 3;
      bctx.lineCap = 'round';
      bctx.beginPath();
      bctx.moveTo(seg.x0 * board.width, seg.y0 * board.height);   // 0..1 → pixels
      bctx.lineTo(seg.x1 * board.width, seg.y1 * board.height);
      bctx.stroke();
      history.push({ seg, color });
      if (history.length > 4000) history.shift();      // cap memory; oldest fade away
    }
    
    // Local drawing: on pointer drag, make a segment, draw it, broadcast it.
    let drawing = false, lastPt = null;
    canvas.addEventListener('pointerdown', (e) => { drawing = true; lastPt = toRoom(e); });
    canvas.addEventListener('pointermove', (e) => {
      const p = toRoom(e); me.x = p.x; me.y = p.y;          // move my cursor too
      if (!drawing) return;
      const seg = { x0: lastPt.x, y0: lastPt.y, x1: p.x, y1: p.y };
      drawStroke(seg, me.color);                          // draw locally first (no round-trip lag)
      send('stroke', { seg, color: me.color });           // then tell the room
      lastPt = p;
    });
    addEventListener('pointerup', () => { drawing = false; lastPt = null; });
    
    // Late-join: a newcomer's board is blank. When someone says hello, offer a snapshot.
    function onHello(toId) {
      const recent = history.slice(-600);                  // cap the snapshot size
      send('snapshot', { to: toId, strokes: recent });    // they replay these in order
    }

    Draw locally first, then broadcast — that order matters. It means your own ink appears instantly with zero perceived latency, and the broadcast is pure fan-out. The history array does double duty: it's how we redraw the board after a resize, and it's how we hand a snapshot to a late-joiner so they don't show up to a mysteriously half-empty board. (More on that trap in the pitfalls — snapshots are best-effort, and that's an honest design choice for a serverless room.)

    Video tiles: a loopback self-view + synthetic peers

    The last layer is faces. We want a self-view tile that's genuinely a WebRTC stream — not just your canvas shown back to you — so you can see the real handshake at work. The pattern is Episode 03's loopback: two RTCPeerConnections in this one page do an actual offer/answer/ICE dance and stream a track to each other. We feed it our synthetic source (or your camera, if you grant it), and the "remote" end of the loopback becomes the self-view tile. Peer tiles for the bots are just more synthetic sources — each a canvas.captureStream() wearing a different hue.

    // A genuine WebRTC handshake with yourself — no server, no second person (Ep03).
    async function rtcLoopback(localStream, onRemoteStream) {
      const A = new RTCPeerConnection(), B = new RTCPeerConnection();
      A.onicecandidate = (e) => e.candidate && B.addIceCandidate(e.candidate);  // trickle
      B.onicecandidate = (e) => e.candidate && A.addIceCandidate(e.candidate);  // straight across
      B.ontrack = (e) => onRemoteStream(e.streams[0]);
      localStream.getTracks().forEach((tr) => A.addTrack(tr, localStream));
      const offer  = await A.createOffer();  await A.setLocalDescription(offer);
      await B.setRemoteDescription(offer);
      const answer = await B.createAnswer(); await B.setLocalDescription(answer);
      await A.setRemoteDescription(answer);                 // exact order matters!
      return { A, B };
    }
    
    // Wire the self-view tile. Wrapped so RTC failure never breaks the room.
    async function addSelfTile(syntheticStream) {
      const v = document.createElement('video');
      v.autoplay = true; v.playsInline = true; v.muted = true;  // muted ⇒ autoplay allowed
      tiles.appendChild(wrapTile(v, me.name + ' (you)', me.color));
      try {
        await rtcLoopback(syntheticStream, (remote) => { v.srcObject = remote; });
      } catch (err) {
        v.srcObject = syntheticStream;                     // fall back: show synthetic directly
        setStatus('loopback unavailable — showing synthetic (' + err.name + ')');
      }
    }

    Every <video> gets muted, autoplay, and playsInline — without muted, browsers refuse to autoplay and your tiles sit black forever. The loopback is wrapped so that if WebRTC is blocked (some locked-down contexts), the tile simply shows the synthetic stream directly and the room carries on. There's that rule again: the upgrade is allowed to fail; the baseline is not.

    Pruning, leaving, and not melting at 60fps

    A room that only ever adds people becomes a graveyard of ghosts. Two things keep the roster honest. First, on a timer we drop any peer whose last timestamp is older than ~4 seconds — if a tab closed without warning, its avatar fades out on its own. Second, we announce departure explicitly on pagehide so a closing tab tells the room goodbye before it dies, instead of leaving a ghost for the timeout to clean up.

    // Heartbeat + prune. Bots are never pruned (they have no 'last' from the network).
    setInterval(() => {
      send('cursor', { x: me.x, y: me.y });          // heartbeat doubles as a liveness ping
      const now = performance.now();
      for (const [id, p] of peers) {
        if (id.startsWith('bot-')) continue;          // bots are local, immortal
        if (now - (p.last || 0) > 4000) peers.delete(id);   // stale ⇒ gone
      }
    }, 800);
    
    // Tell the room you're leaving — pagehide fires on tab close / navigation.
    addEventListener('pagehide', () => send('presence', { bye: true }));
    
    // Throttle outgoing cursors: 60fps of pointermove ⇒ ~20Hz on the wire is plenty.
    let lastCursorSend = 0;
    function maybeSendCursor() {
      const n = performance.now();
      if (n - lastCursorSend > 50) { send('cursor', { x: me.x, y: me.y }); lastCursorSend = n; }
    }

    The throttle is the difference between a smooth room and a stuttering one. A fast mouse fires pointermove dozens of times per frame; blasting every one onto the channel floods other tabs with work. Cap cursor sends to ~20Hz and interpolate the remote pucks toward their targets each frame (the same idea you smoothed in Episode 06) and even a crowded room stays buttery. We also cap the stroke history so the board can't grow without bound.

    Common pitfalls

    • BroadcastChannel is same-origin and same-browser. It's perfect for "open a second tab," but it does not reach another device, another browser, or an incognito window in some browsers. This room is genuinely multiplayer across tabs on one machine — and that's the honest boundary of serverless. Crossing machines needs a signaling server, which is the very first thing Season 2 builds.
    • Late-joiners miss the history. A tab that joins after the drawing started sees a blank-ish board, because BroadcastChannel has no replay. We mitigate with a best-effort snapshot on hello, but it's capped and racy — two tabs may briefly disagree. For a serverless toy that's a fine trade; a real product stores the doc server-side (or in a CRDT) so history is authoritative.
    • Ghost peers. If you only add on message and never expire, closed tabs linger forever. Always pair a pagehide "bye" with a timeout-based prune — networks drop, tabs crash, and the explicit goodbye doesn't always make it out.
    • Video tiles stay black. A <video> won't autoplay unless it's muted (and needs playsInline on iOS). Forget muted and your loopback connects perfectly but shows nothing.
    • Flooding the channel. Sending a cursor on every pointermove and a stroke on every sub-pixel move will saturate other tabs. Throttle cursors (~20Hz), and cap stroke history so memory and redraw cost stay bounded with many peers.
    • Echoing your own messages. BroadcastChannel does not deliver a message back to the sender — but your bots and your local draws do apply locally. Always stamp messages with from: me.id and ignore your own, or you'll double-draw the day you add a relay.
    • Pixel coordinates across tabs. Two tabs are rarely the same size. Send cursor and stroke positions in normalized 0..1 room space and convert to pixels only at draw time, or everyone's ink lands in the wrong spot.

    Exercises

    1. Emoji reactions. Add a reaction message kind. On a keypress (say 1–5), broadcast an emoji + the sender's color, and have every tab spawn a little particle that floats up from that peer's cursor and fades. It's the cheapest possible dopamine and it makes the room feel occupied.
    2. A shared laser pointer. While a modifier key is held, instead of drawing permanent ink, broadcast a transient laser point that everyone renders as a glowing dot which decays after ~600ms (don't push it to history). Great for "look at this" without defacing the board.
    3. Persist the whiteboard. Save history to localStorage (throttled) and rehydrate it on load, so the board survives a refresh and new tabs start from the last saved state instead of an empty snapshot. Then ask yourself: what happens when two tabs persist different histories? Congratulations, you've discovered why Season 2 needs CRDTs.

    What's next — that's a wrap on Season 1

    You did it. From a single animated canvas in Episode 01 to a serverless multiplayer room you can inhabit with a friend (well — a friend at the same computer, in another tab), you've built the entire client-side real-time stack from zero, with no libraries and no backend. Streams, media capture, the WebRTC handshake, data channels, cursor sync, interpolation netcode, broadcast compositing, and now a shared space that ties them all together. That's The Live Web.

    Everything you built has one ceiling, and you've felt it twice now: it can't cross the machine. Season 2 — Production Real-Time knocks that wall down. We add the one piece loopback and BroadcastChannel were standing in for: a signaling server to introduce strangers, then SFUs to scale past a mesh, WebSockets and an authoritative game server, CRDTs for real collaborative editing (the honest version of today's whiteboard), WebTransport, low-latency live streaming, and proper voice/video rooms. Same from-scratch spirit — now with a backend, and now across the planet.

    Take a victory lap, then meet me in Season 2. Bring the room.