Example: A Parallel Mandelbrot Explorer with Workers and Canvas, plus Other Browser APIs
A capstone for the browser part: compute the Mandelbrot set in parallel tiles with a worker pool, transfer typed arrays, paint ImageData on a canvas, zoom with pointer and wheel events, keep the view in the URL, then tour other web platform APIs worth knowing.
kvi5hnuCode Sprout team member8 min readOn this page
This article ties Part 15 together in one application: an explorer for the Mandelbrot set, a famous fractal whose detailed edges are expensive to compute. It uses workers and messaging (article 120), canvas pixel manipulation (article 115), events (article 108), URL and history management (article 116), and core features like generators, private fields and promises. The last section tours other browser APIs you'll meet in real projects.
The math: escape time
For each point c on the complex plane, start with z = 0 and repeat z = z² + c. If |z| ever exceeds 2, the values grow without limit, and c is outside the set. Points that stay bounded are inside. The number of steps before escaping, the escape time, picks the color, which produces the familiar glowing bands around the black set.
Complex numbers are written as x + y·i, so z² + c expands to real part x² − y² + cx and imaginary part 2xy + cy. The core loop is plain arithmetic, which runs anywhere, here as a text rendering:
// How many iterations before z = z² + c escapes (|z| > 2), for c = cx + cy·i
function escapeTime(cx, cy, maxIterations) {
let x = 0, y = 0;
for (let n = 0; n < maxIterations; n++) {
const x2 = x * x, y2 = y * y;
if (x2 + y2 > 4) return n; // escaped: c is outside the set
y = 2 * x * y + cy; // imaginary part of z² + c
x = x2 - y2 + cx; // real part of z² + c
}
return maxIterations; // never escaped: treat as inside
}
console.log(escapeTime(0, 0, 100), escapeTime(-1, 0, 100), escapeTime(1, 1, 100), escapeTime(0.5, 0.5, 100));
// Render a small region as text: " .:-=+*#%@" from fast escape to slow; "@" = inside
const shades = " .:-=+*#%@";
const rows = [];
for (let row = 0; row < 11; row++) {
let line = "";
for (let col = 0; col < 40; col++) {
const n = escapeTime(-2.2 + col * 0.07, -1.1 + row * 0.22, 60);
line += shades[Math.min(shades.length - 1, Math.floor((n / 60) * (shades.length - 1)))];
}
rows.push(line.trimEnd());
}
console.log(rows.join("\n"));
100 100 2 5
.
::@..
.=:.*::@@:::....
. ..*@@@@@@@@@@@@@+.
...@@@@@.=@@@@@@@@@@@@@@@@.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@..
...@@@@@.=@@@@@@@@@@@@@@@@.
. ..*@@@@@@@@@@@@@+.
.=:.*::@@:::....
::@..
.
0 and -1 never escape (inside the set); 1 + i escapes after 2 steps, and 0.5 + 0.5i after 5. A 1000 × 700 image at 1,000 iterations can need up to 700 million loop steps, which is far too slow for the main thread, but a good fit for workers.
Splitting the work
The image is divided into tiles, rectangles that can be computed independently. A pool of workers, typically one per CPU core (navigator.hardwareConcurrency), takes tiles from a queue. As each tile finishes, it's painted immediately, so the picture fills in progressively instead of appearing all at once.

The tile generator and pool are independent of the browser. Here they're tested with stand-in workers built from MessagePorts, which have the same postMessage and onmessage interface as real Worker objects:
// Split a width × height image into tiles that can be computed independently
function* tiles(width, height, size) {
for (let y = 0; y < height; y += size) {
for (let x = 0; x < width; x += size) {
yield { x, y, width: Math.min(size, width - x), height: Math.min(size, height - y) };
}
}
}
// Hands tasks to a fixed set of workers, queueing extras until one is free
class WorkerPool {
#idle = [];
#queue = [];
constructor(workers) {
for (const worker of workers) this.#idle.push(worker);
}
run(task) {
const { promise, resolve, reject } = Promise.withResolvers();
this.#queue.push({ task, resolve, reject });
this.#next();
return promise;
}
#next() {
if (this.#idle.length === 0 || this.#queue.length === 0) return;
const worker = this.#idle.pop();
const { task, resolve, reject } = this.#queue.shift();
worker.onmessage = (event) => {
this.#idle.push(worker);
resolve(event.data);
this.#next();
};
worker.onerror = (event) => {
this.#idle.push(worker);
reject(event.error ?? new Error(event.message));
this.#next();
};
worker.postMessage(task);
}
}
// Stand-ins for real Workers: each answers on its own MessagePort
function fakeWorker(name, log) {
const { port1, port2 } = new MessageChannel();
port2.onmessage = ({ data: tile }) => {
log.push(name);
setTimeout(() => port2.postMessage({ ...tile, pixels: tile.width * tile.height }), 5);
};
return port1; // has postMessage and onmessage, like a Worker
}
async function main() {
const log = [];
const workers = ["w1", "w2", "w3"].map((name) => fakeWorker(name, log));
const pool = new WorkerPool(workers);
const all = [...tiles(250, 100, 64)];
console.log(all.length, "tiles; last:", all.at(-1));
const results = await Promise.all(all.map((tile) => pool.run(tile)));
console.log("pixels:", results.reduce((sum, r) => sum + r.pixels, 0), "=", 250 * 100);
console.log("workers used:", [...new Set(log)].sort().join(", "), "| tasks:", log.length);
for (const worker of workers) worker.close();
}
main();
8 tiles; last: { x: 192, y: 64, width: 58, height: 36 }
pixels: 25000 = 25000
workers used: w1, w2, w3 | tasks: 8
Edge tiles are smaller (58 × 36 here), and all 25,000 pixels are covered exactly once. Three workers process eight tasks, each taking the next tile as soon as it's free.
The worker
Each worker receives a tile, plus the region of the complex plane it covers, and fills a Uint32Array with escape counts. It transfers the buffer back (article 120), so no copy is made:
// mandelbrot-worker.js, loaded with { type: "module" }
import { escapeTime } from "./escape-time.js"; // the function shown above
self.onmessage = ({ data: tile }) => {
const { width, height, x0, y0, step, maxIterations } = tile;
const counts = new Uint32Array(width * height);
for (let row = 0; row < height; row++) {
for (let col = 0; col < width; col++) {
counts[row * width + col] = escapeTime(x0 + col * step, y0 + row * step, maxIterations);
}
}
self.postMessage({ ...tile, counts }, [counts.buffer]);
};
The page
The main script owns the canvas, the view (center, scale, iteration count) and the user interaction:
const canvas = document.querySelector("#fractal");
const ctx = canvas.getContext("2d");
const workerCount = Math.max(1, Math.min(navigator.hardwareConcurrency ?? 4, 8));
const pool = new WorkerPool(
Array.from({ length: workerCount }, () =>
new Worker(new URL("./mandelbrot-worker.js", import.meta.url), { type: "module" })),
);
let view = viewFromURL(location.href); // { cx, cy, scale, maxIterations }
let generation = 0; // increases on every new render
async function render() {
const thisRender = ++generation;
const { width, height } = canvas;
const step = view.scale / width; // complex-plane units per pixel
const x0 = view.cx - (width / 2) * step;
const y0 = view.cy - (height / 2) * step;
const jobs = [...tiles(width, height, 128)].map(async (tile) => {
const result = await pool.run({
...tile, x0: x0 + tile.x * step, y0: y0 + tile.y * step, step, maxIterations: view.maxIterations,
});
if (thisRender !== generation) return; // the user has moved on: drop stale tiles
ctx.putImageData(colorize(result, view.maxIterations), tile.x, tile.y);
});
await Promise.all(jobs);
}
function colorize({ width, height, counts }, maxIterations) {
const image = new ImageData(width, height);
const pixels = new Uint32Array(image.data.buffer); // one 32-bit value per RGBA pixel
for (let i = 0; i < counts.length; i++) {
pixels[i] = counts[i] === maxIterations ? 0xff000000 : palette[counts[i] % palette.length];
}
return image;
}
Details worth noting:
- The generation counter solves a real concurrency problem: if the user zooms while tiles from the previous view are still computing, those late results must not be painted over the new view.
- Viewing
image.data.bufferas aUint32Arraywrites one whole pixel per assignment, with the bytes of0xAABBGGRRin that order on the little-endian hardware almost all devices use (article 79).paletteis a precomputed array of such colors, for example a smooth gradient generated once with HSL math. - The view's scale is measured per pixel, so resizing the canvas shows more of the plane rather than stretching the image.
Interaction and URL state
Clicking zooms in around the clicked point, and holding Shift zooms out. The wheel zooms smoothly, and arrow keys pan. Every change updates the URL, so views can be bookmarked and shared, and Back returns to the previous view:
canvas.addEventListener("pointerdown", (event) => {
const rect = canvas.getBoundingClientRect();
const step = view.scale / canvas.width;
const px = (event.clientX - rect.left) * (canvas.width / rect.width); // CSS -> canvas pixels
const py = (event.clientY - rect.top) * (canvas.height / rect.height);
setView({
...view,
cx: view.cx + (px - canvas.width / 2) * step,
cy: view.cy + (py - canvas.height / 2) * step,
scale: event.shiftKey ? view.scale * 2 : view.scale / 2,
}, { push: true });
});
canvas.addEventListener("wheel", (event) => {
event.preventDefault(); // needs { passive: false }
setView({ ...view, scale: view.scale * Math.exp(event.deltaY * 0.002) });
}, { passive: false });
document.addEventListener("keydown", (event) => {
const pan = { ArrowLeft: [-0.1, 0], ArrowRight: [0.1, 0], ArrowUp: [0, -0.1], ArrowDown: [0, 0.1] }[event.key];
if (!pan) return;
setView({ ...view, cx: view.cx + pan[0] * view.scale, cy: view.cy + pan[1] * view.scale });
});
function setView(next, { push = false } = {}) {
view = next;
const url = viewToURL(view, location.href); // cx, cy, scale, it as query parameters
if (push) history.pushState(view, "", url); // a real step: Back returns here
else history.replaceState(view, "", url); // continuous changes: no history spam
render();
}
window.addEventListener("popstate", (event) => {
view = event.state ?? viewFromURL(location.href);
render();
});
new ResizeObserver(() => {
canvas.width = canvas.clientWidth * devicePixelRatio; // sharp on high-DPI screens
canvas.height = canvas.clientHeight * devicePixelRatio;
render();
}).observe(canvas);
viewToURL and viewFromURL follow the pattern of stateToURL/stateFromURL in article 116, including validating every number read from the URL. Clicks push history entries because they're deliberate steps, while wheel and key changes replace the current entry, so the Back button isn't flooded with tiny steps.
Possible improvements
- Progressive quality: render quickly at low resolution or iteration count, then refine.
- Smooth coloring: use the fractional escape value
n + 1 − log₂(log |z|)to remove visible color bands. - Precision: at extreme zoom (scale below about 1e-13), 64-bit floating-point numbers run out of digits. Deep-zoom renderers use perturbation techniques or arbitrary precision with
BigInt. - OffscreenCanvas: let workers paint directly instead of sending arrays to the main thread.
- Cancellation: tell workers to abandon tiles of an outdated view instead of just discarding their results.
Other browser APIs worth knowing
The web platform is far larger than one book or course part. Here's a map of other APIs, grouped by purpose, with what each is for.
Security and performance
- Content Security Policy (an HTTP header) restricts which scripts, styles and connections a page may use, which is the strongest defense against XSS. Trusted Types enforce safe use of
innerHTML-style sinks. crypto.randomUUID()andcrypto.getRandomValues()for secure random values;crypto.subtlefor hashing, signing and encryption (await crypto.subtle.digest("SHA-256", bytes)).- The Performance APIs:
performance.now(),performance.mark()/measure(),PerformanceObserverfor Core Web Vitals such as LCP and INP, andrequestIdleCallbackfor low-priority work.
Files, binary data and media
Blob,File,FileReaderandblob.text()/arrayBuffer()/stream();URL.createObjectURL(blob)for previews; drag-and-drop files viaevent.dataTransfer.files.CompressionStream/DecompressionStreamfor gzip and deflate, with the Streams API.navigator.mediaDevices.getUserMedia()for camera and microphone,getDisplayMedia()for screen capture,MediaRecorderto record, WebRTC for peer-to-peer audio, video and data, and WebCodecs for low-level encoding and decoding.
App-like features
- Service workers, the Cache API and a web app manifest make Progressive Web Apps installable and usable offline; Push and Notifications deliver messages.
- Clipboard (
navigator.clipboard.writeText()/readText()), Web Share (navigator.share()), Fullscreen (element.requestFullscreen()), the Page Visibility API (document.visibilityState), the Screen Wake Lock API and the<dialog>element and Popover API for native modals and menus. - View Transitions (
document.startViewTransition()) animate between DOM states or pages.
Devices and the environment
- Geolocation (
navigator.geolocation.getCurrentPosition()), device orientation and motion events, the Vibration API, and the Gamepad API. navigator.onLineandonline/offlineevents;navigator.languagewith theIntlAPIs (articles 85 and 86) for formatting.- Permissions (
navigator.permissions.query()) to check before prompting.
Computation and graphics
- WebAssembly runs compiled code from C, C++, Rust or Go at near-native speed, alongside JavaScript:
WebAssembly.instantiateStreaming(fetch("lib.wasm")). It's how tools like image codecs, SQLite and game engines run in the browser. - WebGL and WebGPU for GPU-accelerated 3D graphics and general GPU computation (WebGPU is available in all major browsers as of 2025–2026, though support on some platforms is still rolling out).
Most powerful APIs (camera, location, clipboard reading, notifications) require a secure context (HTTPS) and often a user gesture and an explicit permission. MDN Web Docs is the reference for all of these, with browser compatibility tables for each feature.
Common questions
Why not compute everything on the main thread?
A deep zoom can take seconds of pure computation. On the main thread, that blocks input, scrolling and painting for the whole time, so the page freezes. Workers keep the main thread free to respond, and several workers use several CPU cores.
Why split the image into tiles instead of giving each worker a big strip?
Some regions need far more iterations than others, so equal strips finish at very different times. Many small tiles from a shared queue balance the load automatically: a worker that finishes early just takes the next tile. Tiles also let the picture appear progressively.
Is WebAssembly faster than JavaScript for this?
Often somewhat, for tight numeric loops like this one, but modern JIT compilers make plain JavaScript with typed arrays surprisingly fast. Measure first. Parallelism with workers usually gives a bigger win than switching languages.
Summary
- The Mandelbrot explorer splits an expensive computation into tiles, processes them in a worker pool, transfers typed arrays back and paints each tile with
putImageDataas it arrives. - A generation counter discards stale results when the view changes mid-render, a common pattern for any async rendering.
- Pointer, wheel and keyboard events change the view;
pushStateandreplaceStatekeep it in the URL, andpopstaterestores it. - The wider platform offers APIs for security (CSP, Web Crypto), performance, files and media, offline apps, devices, WebAssembly and GPU graphics. Check MDN and Baseline status before using newer ones.
Review quiz
You've finished Part 15: JavaScript in the Browser. Test yourself with the Part 15 review quiz: 20 questions on scripts and events, the DOM, CSS, geometry, web components, graphics, history, networking, storage and workers.
Practice Questions
A user zooms twice quickly. Tiles from the first zoom arrive after the second render has started. Without the generation check, what goes wrong, and why does the check fix it?
const thisRender = ++generation;
// ...later, when a tile arrives:
if (thisRender !== generation) return;
Answer
Stale tiles computed for the old view would be painted over the new view, leaving a patchwork of two different zoom levels. Each render captures its own generation number. A newer render increments the shared counter, so results from older renders no longer match and are dropped.
Why does the worker transfer its Uint32Array's buffer instead of just posting the array?
self.postMessage({ ...tile, counts }, [counts.buffer]);
Answer
Posting normally copies the data with the structured clone algorithm. Transferring hands over the underlying ArrayBuffer without copying, which matters for large tiles produced many times per second. The worker can no longer use the buffer afterwards (its length becomes 0), which is fine because it creates a new one for the next tile.
Which of these APIs need a secure context (HTTPS), and what else do they usually require: the clipboard read API, geolocation, crypto.getRandomValues?
Answer
Reading the clipboard and geolocation require a secure context, and both also involve a permission prompt (clipboard reading typically also needs a user gesture). crypto.getRandomValues works in any context and needs no permission; only crypto.subtle requires HTTPS.
Previous: Web Workers and Messaging: Threads, postMessage, Transferables and BroadcastChannel
Next: Node.js Fundamentals: Running Programs, Arguments, Environment, Life Cycle and Modules

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.