Real-Time & Streaming From Zero · Episode 01
The Live Web: Streams
The Live Web: Streams is Episode 01 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 fact this entire series is built on: anything you can draw on a
canvas can become a live, broadcast-able video stream. Not a saved file you
upload later — a live signal, the same kind a webcam produces, the same kind you can
pipe into a <video> element, hand to a MediaRecorder,
or shove down a WebRTC connection to someone on the other side of the planet. The
browser does not care whether the pixels came from a camera sensor or from your own
requestAnimationFrame loop. To everything downstream, it's just a stream.
The demo below proves it on first paint, with no camera and no permission prompt.
An animated canvas is being captured into a real MediaStream and played
back through a <video> element right now — the left tile is
the source canvas, the right tile is a video element fed by the stream. Then, with one
click, you can swap that synthetic source for your actual webcam and watch the exact
same pipeline carry it. By the end of this episode you'll own the mental model that the
next twenty-three episodes lean on: tracks → streams → elements (and later,
peers).
What you're looking at
Two tiles and a readout. The left tile is an ordinary
<canvas> with a 2D context, repainting drifting blobs and a live
clock sixty times a second — the clock is there so you can prove with your own eyes
that nothing is a frozen screenshot. The right tile is a
<video> element whose srcObject is a
MediaStream captured from that canvas. The readout along
the bottom lists the actual tracks inside the stream — their kind,
id, and readyState.
Step through the six stages with the stage dropdown; each one lights up
one rung of the ladder from "pixels on a canvas" to "a stream you could send to anyone."
The Use camera button is an opt-in upgrade: it tries
getUserMedia, and if that fails for any reason — denied, no device,
insecure context — it quietly stays on the synthetic source and tells you why. The demo
is never a dead screen.
Stage 1 — A canvas animation
Before anything is a stream, something has to produce pixels. Here it's a 2D canvas
running a requestAnimationFrame loop: a dark field, forty drifting colored
blobs on sine paths, and a timestamp. This is deliberately humble. The point of the
whole episode is that this — a thing you already know how to make — is one
method call away from being live video. The right tile is dark for now: no stream
exists yet.
Stage 2 — captureStream() → a real MediaStream
Call canvas.captureStream(30) and the browser hands you a genuine
MediaStream — the same class getUserMedia returns for a
webcam. The track readout fills in: one video track, with a real
id and a readyState of "live". There is no audio
track, because a canvas makes no sound. Nothing is displayed through a video element
yet; we've only minted the stream. That's the quiet, important step — the canvas is now
a source, indistinguishable downstream from a camera.
Stage 3 — Pipe it into a <video>
Now we connect the stream to the right tile with one assignment:
video.srcObject = stream. The canvas appears, playing "as video," a beat
behind the source (that lag is the encode/decode pipeline doing real work). Crucially
the video element has autoplay, muted, and
playsinline set — without muted the browser would refuse to
autoplay, and on iOS without playsinline it would try to go fullscreen.
Same pixels, now traveling as a media stream instead of a draw call.
Stage 4 — The stream is live and manipulable
A stream isn't a snapshot — it's a tap on a source that's still changing. To prove it, this stage draws an extra overlay on the source canvas: a sweeping band and a "LIVE" stamp. Watch it appear in the right-hand video a frame later, unprompted. You never touched the video element. You changed the source, and the change flowed through the stream automatically. That is the entire promise of live media: edit the source, and every consumer downstream updates for free.
Stage 5 — Enable the camera
This is the upgrade the whole series is built around. Click Use camera
and the demo calls getUserMedia; on success it tears down the synthetic
track, swaps in the camera's video track, and re-points the same video element at the
new stream. Everything downstream — the video tile, the track readout, the badge — keeps
working unchanged, because they only ever spoke "MediaStream," never "camera." If the
camera is unavailable (you denied it, there's no device, or you opened this file over
file://), the status line explains and the synthetic source keeps running.
The alive-state is sacred.
Stage 6 — A stream is just tracks
The payoff mental model. A MediaStream is a thin container; the real
cargo is its MediaStreamTracks. This stage lets you read them with
getVideoTracks() and stop the video track with
track.stop() — watch the readout flip to "ended", the video
freeze, and (if you're on camera) the camera light go out. Tracks are the atoms.
Streams group them; video elements and, later, RTCPeerConnections consume
them. Hold this picture — it's the spine of every episode that follows.
How the code works
Four moving parts carry this whole demo, and they're the same four you'll reuse for the rest of the series. We'll read them in the order the pixels flow.
(a) The synthetic source: a canvas you can turn into a stream
This is the function the entire series defaults to, so the demo is alive with no
camera and no permission. It animates a canvas and — the magic line —
captureStream(fps) returns a real MediaStream from
those drawn pixels. A fake camera, indistinguishable downstream from a real one:
// An animated canvas you can turn into a real MediaStream.
function makeSyntheticSource(w = 640, h = 400, label = 'SYNTHETIC') {
const c = document.createElement('canvas'); c.width = w; c.height = h;
const g = c.getContext('2d');
let t0 = performance.now();
function paint() {
const t = (performance.now() - t0) / 1000;
g.fillStyle = '#0b1020'; g.fillRect(0, 0, w, h);
for (let i = 0; i < 40; i++) { // drifting blobs so motion is obvious
const x = (Math.sin(t * 0.6 + i) * 0.4 + 0.5) * w,
y = (Math.cos(t * 0.5 + i * 1.7) * 0.4 + 0.5) * h;
g.fillStyle = `hsla(${(t * 40 + i * 9) % 360},80%,60%,0.5)`;
g.beginPath(); g.arc(x, y, 18 + 10 * Math.sin(t + i), 0, 7); g.fill();
}
g.fillStyle = '#fff'; g.font = '16px ui-monospace, monospace';
g.fillText(label + ' ' + new Date().toLocaleTimeString(), 16, 28); // a clock proves it's live
requestAnimationFrame(paint);
}
paint();
return { canvas: c, stream: c.captureStream(30) }; // a REAL MediaStream from a fake camera
}
The 30 passed to captureStream is a frame-rate hint: the
stream samples the canvas up to thirty times a second. Pass 0 and the
canvas is only sampled when you explicitly call track.requestFrame() —
handy for slideshow-style sources you don't want burning frames. Omit the argument
entirely and it captures on every canvas change.
(b) Playing a stream: video.srcObject + the autoplay rule
A MediaStream is not a URL, so you never set video.src for
it — you set video.srcObject. And a video element won't autoplay with sound
on the modern web, so it must be muted; on iOS it must also be inline or it hijacks the
screen. These three attributes are non-negotiable for a live tile:
// In HTML: <video autoplay playsinline muted></video>
// muted → browsers only autoplay muted video (no user gesture needed)
// playsinline → iOS plays in the page instead of forcing fullscreen
// autoplay → start as soon as the stream has frames
function play(video, stream) {
video.srcObject = stream; // NOT video.src — a stream is an object, not a URL
video.muted = true; // belt-and-suspenders for the autoplay policy
const p = video.play(); // returns a Promise that can reject
if (p) p.catch(() => {}); // swallow the benign "autoplay blocked" rejection
}
That .catch(() => {}) matters: play() rejects with an
AbortError if you swap srcObject mid-play (we do exactly that
when switching to the camera), and an unhandled rejection would spam the console. We
want zero console errors.
(c) The camera opt-in, with a fallback that never throws
The real upgrade. Only ever call getUserMedia from a user gesture (a
click), and always wrap it so a failure degrades to the synthetic source instead of
blowing up the page. This pattern — try real, catch, fall back to synthetic —
is the contract for the entire series:
async function useCamera() {
try {
return await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
} catch (e) {
// denied, no device, or insecure context (file://) — DON'T throw.
setStatus('camera unavailable — staying synthetic (' + e.name + ')');
return null; // caller keeps the synthetic stream alive
}
}
// Wiring: try the camera; if it returns null we never left synthetic.
cameraBtn.addEventListener('click', async () => {
const cam = await useCamera();
if (!cam) return; // alive-state preserved, no exception escaped
switchSource(cam, 'camera'); // same downstream: srcObject, tracks, badge
});
(d) Inspecting tracks — and stopping them
Finally, the atoms. A stream exposes its tracks; each track has a
kind, an id, a readyState, and a
stop() that genuinely releases the device (this is what turns the camera
light off). Stopping a track does not delete the stream — it just ends that track:
function describe(stream) {
return stream.getTracks().map(tr => ({
kind: tr.kind, // 'video' | 'audio'
id: tr.id.slice(0, 8) + '…',
state: tr.readyState, // 'live' | 'ended'
label: tr.label || '(synthetic)',
}));
}
function stopVideo(stream) {
for (const tr of stream.getVideoTracks()) tr.stop(); // frees the camera; readyState → 'ended'
}
Those four snippets — make a source, play a source, swap in the camera, inspect the tracks — are the complete API surface for this episode. Everything else in the series is a new kind of consumer (a recorder, a peer connection) or a new kind of source (mic, screen). The stream in the middle never changes.
Common pitfalls
- The video stays black. Almost always the autoplay policy: a
<video>won't autoplay unless it'smuted. Addmuted(andplaysinlinefor iOS), and callvideo.play().catch(()=>{})so the benign rejection doesn't surface. - You set
video.srcinstead ofvideo.srcObject. AMediaStreamis an object, not a URL.srcexpects a string and silently does nothing useful with a stream. It's alwayssrcObject. - Camera does nothing over
file://.getUserMediarequires a secure context —httpsorlocalhost. Opening the HTML directly off disk blocks it. That's by design, and exactly why the synthetic source is the default: the demo is fully alive without it. Serve over localhost to try the camera. - The camera light stays on after you "stop." Setting
video.srcObject = nullonly detaches the element. To actually release the device you must calltrack.stop()on every track. Forgetting this is the classic "why is my webcam light still on" bug. - You ignored the
captureStreamfps argument. With no argument the canvas is captured on every change; with0it only captures onrequestFrame(). If your stream looks frozen, check whether you asked for manual capture and never requested a frame.
Exercises
- Two sources, two videos. Call
makeSyntheticSourcetwice with different labels and pipe each stream into its own<video>element. Confirm they animate independently — proof that a "stream" is just a handle, and you can have as many as you like. - Read the real settings. After enabling the camera, log
stream.getVideoTracks()[0].getSettings()and look at the actualwidth,height, andframeRatethe browser chose. (We're not recording yet — just inspecting. Recording is a later episode.) Compare it to whatgetSettings()reports for the synthetic track. - Stream from a file. Add a
<video>that loads a local clip, then callfileVideo.captureStream()on it and pipe that into the output tile. Now your "live source" is a playing video file — same pipeline, different origin — which is exactly how you'd later broadcast a clip to a peer.
What's next
Episode 02 — Getting Real Media: Camera, Mic, and Screen. We graduate
from the synthetic default to the three real capture APIs:
getUserMedia for camera and microphone (and how to enumerate and pick a
specific device), and getDisplayMedia for screen share. We'll handle
permissions gracefully, combine audio and video tracks into one stream, and — true to
the rule we set today — keep the synthetic source as the safety net the moment anything
is denied or unavailable.