Real-Time & Streaming From Zero · Episode 05
Multiplayer Cursors
Multiplayer Cursors is Episode 05 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 .
Here is the single most delightful effect in all of real-time software: you open a document and other people's cursors are already there, gliding around the page, each one named and colored, moving in real time. Figma's whole brand is built on it. Google Docs, Miro, Notion, every collaborative canvas — the moment you see a stranger's arrow drift across your screen, the app stops feeling like a file and starts feeling like a place. It's presence. It's "other people are here."
By the end of this page you'll have built exactly that, with zero
server. Named, colored, buttery-smooth cursors that sync across every browser
tab you have open — open a second tab on this page and your two windows will see each
other move, live. And because a dead room is no fun, we spawn synthetic
bots on Lissajous paths so the space is alive and populated the instant the
page loads, before you open anything. The transport is BroadcastChannel: a
one-line, serverless message bus that every tab of the same origin shares. The data
channel from Episode 04 was the muscle; presence is the choreography.
The badge counts everyone in the room — you, the bots, and every other tab. Watch it jump when a second tab joins.
What you're looking at
The dark panel is a shared room. Your own cursor is the bright arrow that tracks your pointer (the real OS cursor is hidden inside the panel so the custom one feels native). The other arrows are peers: some are bots wandering smooth figure-eight paths, and — the moment you open a second tab — one of them is the real, live cursor from your other window. Each peer carries a name and a color, and a little label rides just below its tip. The badge in the corner is the participant count; the row of colored dots is the avatar list, the same "who's here" strip you see in the top-right of every collaborative app.
Everything here is real. The cross-tab cursors travel over an actual
BroadcastChannel, the same primitive a production app would use for tab
coordination. The only thing synthetic is the bots — and they exist for one
honest reason: so the demo is a party even when you're the only person who has it open.
Step through the six stages with the stage selector to build the effect up
one layer at a time.
Stage 1 — Your cursor
Before anything networks, we own the pointer. We listen for
pointermove on the demo element, convert the event's page coordinates into
coordinates local to the panel, and draw our own cursor there. We also hide the
real OS cursor inside the panel (cursor: none) so the custom one doesn't
fight a system arrow. This is the foundation: a cursor is just an (x, y) we
choose to render ourselves.
One subtlety that matters everywhere in this episode: we store positions as fractions of the panel (0→1), not raw pixels. Your window and the second tab's window are almost certainly different sizes, so a pixel position from one would land in the wrong place in the other. Normalize on send, denormalize on draw, and every peer lines up no matter the viewport.
Stage 2 — Broadcast your position
BroadcastChannel is the unsung hero of serverless multiplayer. You open a
channel by name; every tab, window, and worker on the same origin that opens a
channel with the same name is now wired together. Call postMessage in one
tab and every other tab's onmessage fires. No server, no socket, no
setup — it's built into the browser for exactly this kind of same-origin coordination.
So broadcasting your cursor is one line per move: post {id, x, y} on
pointermove. But "on every move" is a trap — a fast mouse fires
pointermove well over 100 times a second, and flooding the channel wastes CPU
in every listening tab for motion no human can perceive. So we throttle
to about 30 messages per second, which is plenty smooth and a fraction of the traffic:
// (a) Broadcast your cursor on pointermove — THROTTLED to ~30 Hz.
const room = new BroadcastChannel('cursors-demo-room');
const me = { id: Math.random().toString(36).slice(2),
name: randomName(), color: randomColor(), x: 0.5, y: 0.5 };
let lastSent = 0;
const SEND_MS = 1000 / 30; // ~33ms ≈ 30 packets/sec
demo.addEventListener('pointermove', (e) => {
const r = demo.getBoundingClientRect();
me.x = (e.clientX - r.left) / r.width; // store as a 0→1 fraction
me.y = (e.clientY - r.top) / r.height; // (windows differ in size)
const now = performance.now();
if (now - lastSent < SEND_MS) return; // throttle — don't flood
lastSent = now;
room.postMessage({ type: 'move', id: me.id, x: me.x, y: me.y });
});
That's the entire send side. Notice we keep updating me.x/me.y on
every move (so our own cursor is always perfectly smooth — it's local, no
throttle needed) but only broadcast at 30Hz. Local rendering and network
transmission run at different rates, and that's deliberate.
Stage 3 — Render remote cursors
Now the receive side. We keep a Map of peers keyed by their id. When a
message arrives, we look up that peer (creating it if it's new) and update its position.
Then every frame we walk the map and draw each peer's cursor. The one rule you cannot
forget: ignore messages from your own id. BroadcastChannel
delivers to all other tabs but, more importantly, once you have bots and
heartbeats flying around it's easy to echo yourself — so guard against it explicitly.
// (b) The peers Map + receive + render.
const peers = new Map(); // id → { name, color, x, y, tx, ty, last }
room.onmessage = (e) => {
const m = e.data;
if (m.id === me.id) return; // never react to your own echo
let p = peers.get(m.id);
if (!p) { // a tab we haven't seen → it just joined
p = { name: m.name, color: m.color, x: m.x, y: m.y, tx: m.x, ty: m.y };
peers.set(m.id, p);
}
p.tx = m.x; p.ty = m.y; // tx/ty = TARGET (latest) position
if (m.name) p.name = m.name;
if (m.color) p.color = m.color;
p.last = performance.now(); // for presence/pruning (stage 6)
};
function drawPeers() { // called every animation frame
for (const p of peers.values()) drawCursor(p.x * W, p.y * H, p.color, p.name);
}
Open that second tab now and you'll see it: a cursor that isn't yours, moving exactly as your other window's mouse moves. That's two browser tabs talking directly to each other with no backend anywhere. It feels like magic the first time, and it never quite stops feeling like magic.
Stage 4 — Names, colors & smoothing
Two things separate a toy from the Figma feeling. First, identity: every peer gets a stable name and color, assigned once when it joins and carried on its messages. That's what turns anonymous arrows into people. Second, and this is the one everybody gets wrong: smoothing.
Remember we throttled sends to 30Hz. That means a remote cursor's target
position updates only 30 times a second, but you're rendering at 60. If you draw the
cursor directly at the latest received position, it visibly steps — it teleports
from packet to packet, jerky and cheap-looking. The fix is to keep two positions per
peer: the target (tx, ty, the last thing we received) and the
rendered position (x, y), and every frame nudge the rendered one a
fraction of the way toward the target. That's a lerp (linear
interpolation), and it's the difference between "jumpy" and "alive":
// (c) Lerp every rendered cursor toward its latest target, each frame.
function lerp(a, b, t) { return a + (b - a) * t; }
function updatePeers(smoothing) { // smoothing: 0 = snap, ~0.18 = silky
const t = smoothing <= 0 ? 1 : smoothing; // 0 means "no smoothing" → snap
for (const p of peers.values()) {
p.x = lerp(p.x, p.tx, t); // chase the target a little each frame
p.y = lerp(p.y, p.ty, t);
}
}
Drag the smoothing slider while a bot or a second tab is moving. At
0 the cursors snap straight to each raw packet — you can see the
30Hz stepping. Nudge it up and the motion turns liquid. There's a subtle tradeoff: more
smoothing means more visual lag (the cursor trails reality further), so apps tune this to
taste — usually a small value that hides the packet rate without feeling sluggish.
Episode 06 takes this idea much further with proper snapshot interpolation, but a simple
per-frame lerp already gets you 90% of the way there.
Stage 5 — Synthetic bots
A presence demo that's empty until a second human shows up is a broken demo. So we populate the room ourselves with bots: fake peers that wander the panel on smooth, hypnotic paths. The trick for organic-looking motion is a Lissajous curve — two sine waves at different frequencies driving x and y. Give each bot its own frequencies and phase offset and they each trace a unique looping figure that never repeats the same way twice:
// Bots are just peers whose position is a function of time (Lissajous paths).
function makeBot(i) {
return {
name: BOT_NAMES[i % BOT_NAMES.length],
color: `hsl(${(i * 67) % 360},75%,62%)`,
ax: 0.6 + Math.random() * 0.7, ay: 0.7 + Math.random() * 0.8, // frequencies
px: Math.random() * 6.28, py: Math.random() * 6.28, // phase offsets
x: 0.5, y: 0.5,
};
}
function updateBots(time) {
for (const b of bots) {
// map sine (-1→1) into the 0.08→0.92 safe area of the panel
b.x = 0.5 + 0.42 * Math.sin(time * b.ax + b.px);
b.y = 0.5 + 0.40 * Math.sin(time * b.ay + b.py);
}
}
Bots render through the exact same drawCursor path as real
peers — they're indistinguishable on screen, which is the point. Drag the
bots slider from 0 to 8 to add or remove them. Because they share the render
path with the network peers, the demo looks identically alive whether you have one tab
open or five.
Stage 6 — Presence: join, leave & pruning
The last layer is presence — knowing who is actually here right
now. Three mechanisms make it robust. A peer announces itself with a
join when it starts and sends a periodic heartbeat so others
know it's still alive. When a peer closes its tab, the pagehide event fires
and we broadcast a leave so everyone removes it immediately. But tabs don't
always get to say goodbye — a crash, a force-quit, a killed process — so we also
prune: any peer we haven't heard from in a few seconds is presumed gone
and dropped from the map. Heartbeat + explicit leave + timeout prune is the classic,
bulletproof recipe:
// (d) Presence: heartbeat, prune stale peers, say goodbye on pagehide.
const HEARTBEAT_MS = 1500; // announce "still here" twice a second-ish
const TIMEOUT_MS = 4000; // no word in 4s → assume the tab is gone
room.postMessage({ type: 'join', id: me.id, name: me.name, color: me.color });
setInterval(() => { // HEARTBEAT — keeps us in others' lists
room.postMessage({ type: 'beat', id: me.id, name: me.name, color: me.color });
}, HEARTBEAT_MS);
function prune() { // drop peers that went silent
const now = performance.now();
for (const [id, p] of peers) {
if (now - p.last > TIMEOUT_MS) peers.delete(id);
}
}
// Say goodbye when the tab closes (pagehide is the reliable one, not unload).
addEventListener('pagehide', () => {
room.postMessage({ type: 'leave', id: me.id });
});
// In room.onmessage, handle leave explicitly:
// if (m.type === 'leave') peers.delete(m.id);
The participant count is now just 1 + peers.size (you, plus everyone
else), and the avatar strip is a dot per peer in its color. Open a second tab and watch
the count tick up and a new dot appear; close it and watch the leave remove
it instantly — or, if you kill it ungracefully, watch the prune sweep it away a few
seconds later. That's a complete, honest presence system in about thirty lines, no
backend in sight.
Why this works with no server
It's worth saying plainly what just happened, because it feels impossible the first time. There is no signaling server, no WebSocket, no database. Two tabs of the same site, in the same browser, share an in-browser message bus that the browser itself routes between them. You named a channel; the browser connected everyone who used that name. That's the whole architecture:
The catch — and it's the one limitation to internalize — is in that middle box: it's the browser, on this machine. We'll dig into exactly why that matters, and what to reach for when you outgrow it, in the pitfalls.
Common pitfalls
- BroadcastChannel is same-origin, same-browser, cross-tab only. This is the big one. It connects tabs and windows of the same site on one machine — it does not reach another device, another person's laptop, or even a different browser on the same computer. It's perfect for "open a second tab" and for syncing tabs of a logged-in user, but real multiplayer across devices needs a server to relay messages. That signaling server is Season 2; everything you learn here is the client-side half that stays identical once a relay is added.
- Flooding the channel.
pointermovefires faster than 120Hz on a good mouse. Posting every event hammers the CPU of every listening tab for motion nobody can see. Throttle to ~30Hz (some apps go as low as 20Hz for cursors and let smoothing cover the gap). Sending the freshest position at a capped rate always beats sending every position. - Reacting to your own messages. Always guard
if (m.id === me.id) return;.BroadcastChannelwon't echo to the same channel object, but the instant you have multiple channels, bots, or a shared room id, self-messages sneak in and you get a ghost cursor fighting your real one. - Never pruning stale peers. Tabs crash, get force-quit, or sleep
without firing
pagehide. If you only remove peers on an explicitleave, dead cursors accumulate and freeze on screen forever. Always pair the leave message with a heartbeat-and-timeout prune so silence eventually cleans itself up. - Snapping to raw packets (no smoothing). Drawing remote cursors directly at each received position makes them visibly step at the send rate. Keep a target and a rendered position and lerp between them every frame. Raw = jumpy; lerped = liquid. (Don't over-smooth either, or cursors lag noticeably behind reality.)
- Sending pixels instead of fractions. Two windows are different
sizes. A pixel
(840, 300)from a wide window lands off-screen in a narrow one. Normalize to 0→1 on send and multiply back up on draw so every peer aligns regardless of viewport. - Using
unloadfor goodbye. Theunloadevent is unreliable and blocks back/forward caching; modern browsers may skip it.pagehide(andvisibilitychange) are the dependable signals for "this tab is going away."
Exercises
- Click ripples that broadcast. On
pointerdown, post a{type:'click', id, x, y}message and draw an expanding, fading ring at that spot — locally and on every peer that receives it. Now a click in one tab blooms in all of them. It's the same pattern as cursor moves, but for discrete events instead of a continuous stream, and it's wildly satisfying. - Show each peer's selection or typing. Add a tiny text field under
the demo. As a peer types, broadcast
{type:'label', id, text}(throttled), and render the text in a little bubble that follows their cursor — a live "Sara is typing…" tag. This is exactly how collaborative editors show remote selections and carets. - A "follow me" button. Broadcast your viewport
(
{type:'viewport', id, scrollY, zoom}) and, when another peer clicks "follow," smoothly move their view to match yours. It's Figma's "spotlight" feature in a dozen lines, and it teaches that presence isn't only cursors — any shared state travels the same channel.
What's next
Episode 06 — State sync & interpolation: hide the lag. Our lerp smoothing was a first taste; next we make latency genuinely disappear. We add a slider-driven fake network delay (the way real packets actually arrive — late and jittery), then buffer incoming snapshots and interpolate between the last two so remote motion stays perfectly smooth even over a bad connection. Then we go further: client-side prediction and reconciliation, the netcode every multiplayer game uses to make a laggy link feel instant. The cursors you just synced are about to learn how to lie convincingly about time.