Canvas and WebGL performance
Measure what each canvas frame costs, size the bitmap for the device pixel ratio, draw in a worker with OffscreenCanvas, and know when WebGL or WebGPU helps.
- 01Find a canvas frame's costTell the JavaScript that gives drawing commands from the work of making pixels, and cut both.
- 02Size a canvas for the screenUse the device pixel ratio to keep a canvas sharp, and know what its bitmap costs in memory and time.
- 03Move drawing off the main threadDraw in a worker with OffscreenCanvas, and know when WebGL or WebGPU can draw much more for less.
The steam stopped, and the leaf kept swaying
Asha is back on Leaf and Kettle's mint tea reviews. Ravi has a new idea. At the top of the page, he put Ben's photo of his glass of mint tea. Over the photo sits a canvas: an HTML element that JavaScript paints pixels on, as in lesson 27.4. On it, puffs of steam rise from the glass.
Asha taps Helpful on Ravi's review. The green +1 rises, and the leaf by the title keeps swaying. But the steam stops in mid-air. A moment later, it jumps and carries on. Here is what she saw, in real frames from Chrome:
Here are the main numbers as code:
// Asha taps Helpful. The steam, and DevTools' Frames track, for 850 ms.const ranking = { startsAt: 151.2, lastsMs: 400.1 };const steam = { framesDuringRanking: 0, longestGapMs: 413.5 };const frames = { presented: 28, partiallyPresented: 23 }; console.log(`Ravi's ranking code ran for ${ranking.lastsMs} ms.`);console.log(`The steam drew ${steam.framesDuringRanking} frames in that time.`);console.log(`${frames.partiallyPresented} of ${frames.presented + frames.partiallyPresented} frames were partially presented.`);- Line 1 is a comment. A millisecond (ms) is a thousandth of a second. A frame is one picture on the screen. DevTools' Frames track shows each one, as in lesson 32.4.
- Line 2 holds when Ravi's ranking code started after the tap, and how long it ran. It's the same 400 ms of work as in lesson 32.1.
- Line 3 holds the steam: the frames it drew while the ranking code ran, and the longest gap between two of its frames.
- Line 4 counts Chrome's frames by kind.
- Line 6 prints
Ravi's ranking code ran for 400.1 ms.Line 7 printsThe steam drew 0 frames in that time. - Line 8 prints
23 of 51 frames were partially presented.
So the steam waited 413.5 ms between two of its frames. Chrome kept showing frames, with the leaf in a new place each time. But 23 of them came without new steam. Lesson 32.4's sorting game had this very case: a canvas animation on the main thread, late while the rest of the page moves on.
Why did the leaf keep going? It's a CSS animation. Chrome hands it to the compositor, which moves it by itself, as lesson 32.1 showed. A canvas is different. It shows only what your JavaScript drew. Ravi's code draws the steam in a requestAnimationFrame callback, once before each frame. That callback runs on the main thread, the one that runs the page's JavaScript. While the ranking code ran, no callback could run. So no new steam was drawn.
Ravi makes a flip book of steam for the shop counter. He draws each page by hand, just before it's shown. Then the phone rings. While he talks, no new pages get drawn, and the steam stands still. The paper windmill on the counter keeps turning. The wind moves it, not Ravi.
- In real life: Each page of the flip book
- In JavaScript: Each frame of the canvas
- In real life: Ravi drawing a page just before it's shown
- In JavaScript: A requestAnimationFrame callback drawing the steam
- In real life: The phone call
- In JavaScript: Ravi's ranking code, a long task on the main thread
- In real life: The paper windmill, turned by the wind
- In JavaScript: The leaf's CSS animation, run by the compositor
A canvas animation costs time in every frame. JavaScript gives the drawing commands, and the browser turns them into pixels. Keep each frame's commands few and cheap. Keep the bitmap no bigger than the screen needs. And draw where the page's other work can't block you.
This lesson takes four steps. First, what one frame costs. Then the canvas's size on sharp screens. Then drawing in a worker. Last, drawing with the GPU, through WebGL and WebGPU.
How the course recorded it
- The browser: Chrome 157, with a screen the size of Asha's phone, 412 by 823 px. Its main thread was slowed 4 times, as in lessons 32.1 to 32.4. That slows the main thread only, not workers or the GPU.
- The GPU: Chrome drew with the laptop's real graphics chip, an Apple M1 Pro. WebGL named it
ANGLE (Apple, ANGLE Metal Renderer: Apple M1 Pro, Unspecified Version). It wasn't SwiftShader, the GPU made of software that headless Chrome uses on Linux. A laptop's GPU is much faster than a phone's. So treat the GPU's numbers as a best case. - The pages: Ravi's page, drawn 21 ways: different drawing code, sizes, options, a worker and WebGL. Each calm page was measured for one second.
- The taps: a real mouse click on Helpful, once untimed, then 3 times. The numbers come from the middle tap. DevTools' own trace engine read every trace, so each count is what the Frames track shows. Your times will differ.
What one frame of steam costs
First, where each puff is. Ravi wrote two small helpers:
// steam.js: where each puff of steam is, at any moment.function makePuffs(count) { return Array.from({ length: count }, (_, i) => ({ x: 150 + ((i * 37) % 80), // where it starts, across the glass speed: 0.25 + ((i * 13) % 10) / 40, // it rises in 2 to 4 seconds start: (i * 0.618) % 1, // how far up it starts }));} function place(puff, now) { const life = (puff.start + (now / 1000) * puff.speed) % 1; // 0 at the glass, 1 at the top return { x: puff.x + Math.sin(life * 6 + puff.x) * 10 * life, y: 60 - life * 70, r: 3 + life * 9, a: 0.9 * (1 - life), };}- Lines 2 to 8 make the puffs. Each one gets a place across the glass, a speed and a starting height.
- Lines 10 to 18 work out where a puff is at a moment. On line 11,
lifegoes from 0 at the glass to 1 at the top, then starts again. - Lines 13 to 16 make the puff rise, drift, grow and fade as its life goes on.
Each frame, the callback runs drawSteam(). Here is Ravi's first version:
function drawSteam(ctx, puffs, now) { ctx.clearRect(0, 0, 380, 150); for (const puff of puffs) { const { x, y, r, a } = place(puff, now); ctx.fillStyle = `rgba(255, 255, 255, ${a})`; ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill(); }}- Line 2 clears the canvas. Line 3 loops over the 500 puffs, and line 4 asks where each one is now.
- Line 5 sets the colour: white, as see-through as the puff's fade.
- Lines 6 to 8 draw one circle and fill it.
Where the pixels are made
Those calls don't paint pixels on the spot. Chrome writes each one down as a drawing command. Later, the commands become pixels. That step is called raster, as in lesson 31.4. Where it happens depends on where the canvas keeps its pixels, its bitmap:
- A GPU canvas keeps its bitmap on the GPU, the graphics chip. Raster happens there, in Chrome's GPU process. The HTML standard calls this "hardware accelerated".
- A CPU canvas keeps its bitmap in ordinary memory. Raster happens on the thread that draws. For Ravi, that's the main thread. The standard calls this "software".
Chrome picks the GPU for a 2D canvas when it can use one. Its source, html_canvas_element.cc, makes that choice. It picks the CPU when the page asks for willReadFrequently: true. More on that option below.
Four ways to draw the same steam
Ravi tried four ways to draw the same 500 puffs. The last three follow tips from MDN's page Optimizing canvas:
- One puff at a time: the code above.
- Soft shadows: the same, plus
shadowBlurfor a soft edge. MDN says to avoid it "whenever possible". - One path: every circle in one path, filled once. MDN says: "Batch canvas calls together."
- A stamp: draw one soft puff once, then copy it for every puff. MDN calls this pre-rendering.
const stamp = new OffscreenCanvas(24, 24); // one soft puff, drawn onceconst pen = stamp.getContext("2d");const glow = pen.createRadialGradient(12, 12, 0, 12, 12, 12);glow.addColorStop(0, "white");glow.addColorStop(1, "rgba(255, 255, 255, 0)");pen.fillStyle = glow;pen.fillRect(0, 0, 24, 24); function drawSteam(ctx, puffs, now) { ctx.clearRect(0, 0, 380, 150); for (const puff of puffs) { const { x, y, a } = place(puff, now); ctx.globalAlpha = a; ctx.drawImage(stamp, Math.round(x) - 12, Math.round(y) - 12); }}- Line 1 makes a small canvas of its own, 24 by 24 pixels. An
OffscreenCanvasis a canvas with no element on the page. - Lines 3 to 7 paint one soft puff: white in the middle, see-through at the edge.
- In drawSteam(), line 13 sets how see-through the next copy is. Line 14 copies the stamp at whole-pixel positions, at its own size, as MDN suggests.
Here is what each way cost, as code:
// 500 puffs. Main-thread time per frame, in ms, with the main thread 4 times slower.const ways = [ { way: "one puff at a time", js: 1.8, gpuCanvas: 3.2, cpuCanvas: 6.1 }, { way: "soft shadows", js: 1.8, gpuCanvas: 3.5, cpuCanvas: 20.3 }, { way: "one path", js: 0.2, gpuCanvas: 1.9, cpuCanvas: 5.6 }, { way: "a stamp", js: 1, gpuCanvas: 3.5, cpuCanvas: 3.6 },];for (const w of ways) { console.log(`${w.way}: ${w.js} ms of JavaScript, ${w.gpuCanvas} ms on a GPU canvas, ${w.cpuCanvas} ms on a CPU canvas`);}- Lines 3 to 6 hold one way each.
jsis the time inside the callback. The other two are the main thread's whole time for the frame. - The CPU canvas is the same page with
willReadFrequently: true. - Line 9 prints one line per way. The second is
soft shadows: 1.8 ms of JavaScript, 3.5 ms on a GPU canvas, 20.3 ms on a CPU canvas.
Fewer calls, less JavaScript. One path needed 0.2 ms of JavaScript. One puff at a time needed 1.8 ms, about nine times as much. Each call costs a little. Changing the colour 500 times is 500 more calls. Why it matters: when a frame does the same thing many times, batch it.
Shadows hide from your JavaScript. Soft shadows took 1.8 ms of JavaScript, the same as plain circles. The blur is paid during raster. On the GPU canvas, the GPU process was busy for 87.2 ms in that second, instead of 26.8 ms. On the CPU canvas, the main thread paid: 20.3 ms a frame. That's more than a whole frame at 60 Hz. Why it matters: time the whole frame, not just your function.
The stamp makes its soft edge once. On the CPU canvas, it took 3.6 ms a frame, against 20.3 ms for soft shadows. Copying a ready-made picture is cheap anywhere. Why it matters: draw anything that repeats once, then copy it.
Leaf and Kettle prints a leaf on every paper bag. Ravi used to paint each one by hand. He washed his brush for every new shade of green. Then he carved a rubber stamp. Carving took an hour, once. Now each bag takes one press.
- In real life: Painting each leaf by hand
- In JavaScript: Calling arc() and fill() for every puff
- In real life: Washing the brush for a new shade
- In JavaScript: Setting a new fillStyle, a state change
- In real life: Carving the stamp, once
- In JavaScript: Drawing one soft puff on a small OffscreenCanvas
- In real life: One press per bag
- In JavaScript: One drawImage() per puff
Try each way, and compare the two kinds of canvas:
function drawSteam(ctx, puffs, now) {
ctx.clearRect(0, 0, 380, 150);
for (const puff of puffs) {
const { x, y, r, a } = place(puff, now);
ctx.fillStyle = `rgba(255, 255, 255, ${a})`;
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2);
ctx.fill();
}
}1.8 ms3.2 ms6.1 ms26.8 ms8.6 ms0 of 60Every puff gets its own colour, its own path and its own fill. The JavaScript lists four commands per puff.
Reading pixels back
Some pages read their pixels back. Ravi tried a fading trail. Each frame reads the last frame, makes it fainter, puts it back, then stamps the new puffs:
function drawSteam(ctx, puffs, now) { const last = ctx.getImageData(0, 0, 380, 150); // read the last frame back for (let i = 3; i < last.data.length; i += 4) last.data[i] *= 0.8; // fade it ctx.putImageData(last, 0, 0); for (const puff of puffs) { const { x, y, a } = place(puff, now); ctx.globalAlpha = a; ctx.drawImage(stamp, Math.round(x) - 12, Math.round(y) - 12); }}- Line 2 reads every pixel with
getImageData(). It returns red, green, blue and alpha for each pixel, as in lesson 27.5. Alpha is how see-through a pixel is. - Line 3 visits every fourth number, the alpha, and makes it 80% as strong.
- Line 4 puts the pixels back with
putImageData().
On a GPU canvas, the pixels live on the GPU. Reading them means waiting for the GPU, then copying them over. The HTML standard says most drawing is faster on a GPU canvas, "with the major exception being readback". So it offers an option:
const ctx = canvas.getContext("2d", { willReadFrequently: true });Line 1 passes willReadFrequently: true. It says the page will read its pixels often. The standard says a CPU canvas is then the better choice.
Chrome also helps when you forget. Its source, base_rendering_context_2d.cc, counts the reads. Without the option, the second read moves the canvas to the CPU. Chrome also writes a warning in the Console. In the course's recording, only the page without the option got the warning.
There's a catch. A CPU canvas makes every pixel on the main thread. You saw the bill above: soft shadows went from 3.5 ms to 20.3 ms a frame. And on the course's laptop, reading from the GPU canvas was quick anyway. Each read took a median of 1.0 ms with willReadFrequently: false, and 1.2 ms with true. That's this laptop's GPU. Readback speed depends on the device, so measure on the phones your visitors use. Why it matters: ask for a CPU canvas only when the page really reads often.
Leaf and Kettle keeps most of its tea in a warehouse across town. Its machines pack orders fast. But to count one shelf, Meera has to phone and wait. A small back room keeps the tea close. Counting is quick there, but Meera packs every order herself.
- In real life: The warehouse's fast machines
- In JavaScript: A GPU canvas: raster on the GPU
- In real life: Phoning to count a shelf
- In JavaScript: getImageData() on a GPU canvas
- In real life: The back room
- In JavaScript: A CPU canvas, with willReadFrequently: true
- In real life: Meera packing every order herself
- In JavaScript: Raster on the main thread
Device pixel ratio and canvas size
Asha's phone has a sharp screen. CSS sizes things in CSS pixels. The screen draws each one with several of its own pixels, its device pixels. How many device pixels fit across one CSS pixel is the device pixel ratio. JavaScript reads it as devicePixelRatio.
MDN says phone screens "often yield a devicePixelRatio value greater than 2." The course gave Asha's phone a ratio of 3, with DevTools' device settings.
A canvas has two sizes:
- Its CSS size is how big it looks. Ravi's fills 380 by 150 CSS pixels.
- Its bitmap size is how many pixels it holds. Only its
widthandheightattributes set it. CSS just stretches the bitmap, the way it stretches a photo.
Ravi's canvas has width="380" and height="150". On a 3x screen, each bitmap pixel is stretched over 3 by 3 device pixels, and edges look soft. To keep it sharp, Ravi follows MDN's pattern:
const canvas = document.querySelector("#steam");const dpr = devicePixelRatio; // 3 on Asha's phonecanvas.width = 380 * dpr;canvas.height = 150 * dpr;const ctx = canvas.getContext("2d");ctx.scale(dpr, dpr); // keep drawing in CSS pixelsconst puffs = makePuffs(500); requestAnimationFrame(function frame(now) { drawSteam(ctx, puffs, now); requestAnimationFrame(frame);});- Line 2 reads the ratio: 3 on Asha's phone.
- Lines 3 and 4 make the bitmap 3 times wider and 3 times taller.
- Line 6 scales all drawing by 3. So drawSteam() keeps working in CSS pixels.
That's 9 times the pixels, not 3. Each pixel takes 4 bytes of memory: red, green, blue and alpha. Lesson 31.4's memory estimate counts them the same way.
// Ravi's canvas fills 380 by 150 CSS pixels.for (const dpr of [1, 3]) { const width = 380 * dpr; const height = 150 * dpr; const bytes = width * height * 4; // red, green, blue and alpha console.log(`${dpr}x: ${width} by ${height}, ${width * height} pixels, ${(bytes / 1e6).toFixed(1)} MB`);}- Line 2 tries a ratio of 1, then 3. Lines 3 and 4 work out the bitmap's size.
- Line 5 counts 4 bytes for each pixel.
- It prints
1x: 380 by 150, 57000 pixels, 0.2 MBand3x: 1140 by 450, 513000 pixels, 2.1 MB.
Ravi tiles the shop's floor. With big tiles, it takes 100. Tiles a third as wide look finer. But now the same floor takes 900, and each one must still be bought and laid.
- In real life: The floor
- In JavaScript: The canvas's CSS size: 380 by 150
- In real life: One tile
- In JavaScript: One bitmap pixel
- In real life: Tiles a third as wide
- In JavaScript: A bitmap for a ratio of 3
- In real life: Buying and laying each tile
- In JavaScript: The memory and raster time of each pixel
The course drew 500 plain circles at both sizes. Their hard edges show any blur. On the GPU canvas, the main thread barely noticed: 3.3 ms a frame at 1x, and 3.4 ms at 3x. The commands were the same, and the GPU made the extra pixels.
On the CPU canvas, the main thread made every pixel: 6.3 ms a frame at 1x, and 11.5 ms at 3x. Why it matters: a sharp canvas costs 9 times the memory on any screen, and much more time on a CPU canvas.
You can choose. For speed, MDN's WebGL page suggests a smaller bitmap at the same CSS size. A ratio of 2 gives 4 times the pixels instead of 9. Try the three canvases:
const canvas = document.querySelector("#steam");
const dpr = devicePixelRatio; // 3 on Asha's phone
canvas.width = 380 * dpr;
canvas.height = 150 * dpr;
const ctx = canvas.getContext("2d");
ctx.scale(dpr, dpr); // keep drawing in CSS pixels
const puffs = makePuffs(500);
requestAnimationFrame(function frame(now) {
drawSteam(ctx, puffs, now);
requestAnimationFrame(frame);
});1140 by 450513,0002.1 MB3.4 ms11.5 msNot read yetOne bitmap pixel for every device pixel: 9 times the pixels. Sharp, and on a CPU canvas, much slower to fill.
OffscreenCanvas: drawing in a worker
Back to Asha's tap. The steam stopped because its callback runs on the main thread. The ranking code held the main thread for 400 ms. Cheaper drawing can't fix that. The drawing has to move.
Lesson 27.4 moved Meera's chart into a worker: a second JavaScript thread with no page of its own. It handed the canvas over like a window dresser with her own door. Ravi does the same for the steam:
const canvas = document.querySelector("#steam");const offscreen = canvas.transferControlToOffscreen();const worker = new Worker("steam-worker.js");worker.postMessage({ canvas: offscreen }, [offscreen]);- Line 2 calls
transferControlToOffscreen(). It returns an OffscreenCanvas. The canvas on the page now shows what the worker draws. - Line 3 starts the worker. Line 4 sends it the canvas, in the transfer list: it moves, it isn't copied.
The worker's file starts with the same makePuffs(), place(), stamp and drawSteam(). Then it starts the steam:
onmessage = (event) => { const ctx = event.data.canvas.getContext("2d"); const puffs = makePuffs(500); requestAnimationFrame(function frame(now) { drawSteam(ctx, puffs, now); requestAnimationFrame(frame); });};- Line 1 waits for the canvas. Line 2 gets its drawing context.
- Lines 4 to 7 are the same frame loop as before. The HTML standard gives
requestAnimationFrameto dedicated workers too.
Where do a worker's frame callbacks come from? Not from the main thread. In Chromium, each worker gets its own BeginFrameProvider. It opens its own line to the display compositor, the part of Chrome that puts every frame on the screen. So the worker hears about each frame directly. Its finished drawings go to the screen without the main thread, as the HTML standard encourages.
Here is the same tap, with the steam in a worker:
// The same tap, with the steam drawn by a worker.const ranking = { startsAt: 150.6, lastsMs: 400.6 };const steam = { framesDuringRanking: 24, longestGapMs: 18.6 };const frames = { presented: 51, partiallyPresented: 0 }; console.log(`Ravi's ranking code ran for ${ranking.lastsMs} ms.`);console.log(`The steam drew ${steam.framesDuringRanking} frames in that time.`);console.log(`${frames.partiallyPresented} of ${frames.presented + frames.partiallyPresented} frames were partially presented.`);- Lines 2 to 4 hold the same three things as the first example, for the worker's page.
- It prints
Ravi's ranking code ran for 400.6 ms.,The steam drew 24 frames in that time.and0 of 51 frames were partially presented.
The ranking code ran just as long. But the steam drew 24 frames through it. Its longest gap was 18.6 ms, not 413.5 ms. Every frame was presented. Why it matters: when a page has other heavy work, an animation drawn in a worker keeps its beat.
The shop window has a puppet that pours tea. Meera used to work it between customers. When a big order came in, the puppet froze mid-pour. Now a puppeteer stands behind the window and does nothing else. Meera takes any order, and the puppet keeps pouring.
- In real life: Meera, serving customers
- In JavaScript: The main thread
- In real life: A big order
- In JavaScript: Ravi's ranking code
- In real life: The puppet in the window
- In JavaScript: The steam on the canvas
- In real life: Handing over the strings
- In JavaScript: transferControlToOffscreen()
- In real life: The puppeteer
- In JavaScript: The worker, drawing every frame
Three things to know before you move a canvas:
- The worker isn't faster. It runs the same drawing code. DevTools couldn't slow a worker in lesson 27.4, so this one ran at the laptop's full speed. A phone's slower cores would take longer per frame. The worker still wouldn't wait for the main thread.
- Size the canvas first. After the hand-over, the page can't change the canvas's width or height. Set them before, or set the OffscreenCanvas's size in the worker.
- Taps stay on the page. A worker can't see taps or the page's elements. If the steam must follow a finger, the page sends each position with
postMessage(). Those messages still need the main thread.
Try it in your own browser. Watch the steam, then block the main thread. Then switch to the worker and do it again. You can also open the course's copies: the steam on the main thread and the steam in a worker.
const canvas = document.querySelector("#steam");
const ctx = canvas.getContext("2d");
const puffs = makePuffs(500);
requestAnimationFrame(function frame(now) {
drawSteam(ctx, puffs, now);
requestAnimationFrame(frame);
});const end = performance.now() + 400;
while (performance.now() < end) {} // stands in for Ravi's ranking codePress Keep the main thread busyThe steam is 500 puffs, drawn the stamp way. The button blocks this page's main thread for 400 ms, as Ravi's ranking code did.
WebGL and WebGPU basics
Ravi gets carried away. He wants 5,000 puffs, ten times as many. With the stamp, that's 5,000 drawImage() calls a frame. He also tries WebGL, a way to draw with the GPU directly:
// 5,000 puffs for one second, the main thread 4 times slower.const many = [ { way: "2D canvas, a stamp", msPerFrame: 28.1, frames: 35, late: 25 }, { way: "WebGL", msPerFrame: 1.4, frames: 60, late: 0 },];for (const m of many) { console.log(`${m.way}: ${m.msPerFrame} ms a frame, ${m.late} of ${m.frames} frames late`);}- Lines 3 and 4 hold each page: main-thread time per frame, frames in one second, and how many came late.
- It prints
2D canvas, a stamp: 28.1 ms a frame, 25 of 35 frames lateandWebGL: 1.4 ms a frame, 0 of 60 frames late.
The 2D canvas fell behind. Each frame took longer than a frame lasts, so Chrome showed only 35 frames, and 25 were partially presented. WebGL drew the same puffs with 1.4 ms of main-thread time a frame, and every frame was on time.
WebGL is another kind of drawing context for a canvas: canvas.getContext("webgl"). WebGL 1 and 2 follow OpenGL ES 2.0 and 3.0, an older graphics API. You write small programs called shaders, which run on the GPU. A vertex shader places each point. A fragment shader colours each pixel.
attribute vec3 puff; // x, speed and start, as in makePuffs()uniform float now;varying float alpha;void main() { float life = fract(puff.z + now / 1000.0 * puff.y); float x = puff.x + sin(life * 6.0 + puff.x) * 10.0 * life; float y = 60.0 - life * 70.0; gl_Position = vec4(x / 190.0 - 1.0, 1.0 - y / 75.0, 0.0, 1.0); gl_PointSize = 24.0; alpha = 0.9 * (1.0 - life);}- Line 1: each puff arrives as three numbers, x, speed and start, from makePuffs().
- Line 2:
nowis the frame's time. It's the one number JavaScript sends each frame. - Lines 5 to 7 are place() again, in the shader's language. The GPU runs them for many puffs at once.
- Line 8 turns the puff's place into the GPU's own coordinates. Line 9 makes each puff 24 pixels wide, like the stamp.
requestAnimationFrame(function frame(now) { gl.uniform1f(nowAt, now); // the only number that changes gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.POINTS, 0, 5000); // every puff, in one call requestAnimationFrame(frame);});- Line 2 sends the new time. Line 3 clears the canvas.
- Line 4 draws every puff with one call.
Setting WebGL up takes more code: compiling the shaders, and sending every puff's numbers to the GPU once. The course's copy of the page has it all. But each frame is just these few calls. MDN's WebGL best practices says: "If you have 1000 sprites to paint, try to do it as a single drawArrays() or drawElements() call." It's like a printing press: setting up the plate takes a while, then one pull prints the whole sheet.
Remember what drew it: a laptop's GPU. Its GPU process was busy for 20.1 ms in that second with WebGL, and 116.5 ms with the 2D canvas. A phone's GPU is slower. But the main thread was already 4 times slower here, and its share stayed small. Why it matters: for thousands of things, the number of calls per frame decides the cost.
WebGL has one trap. Some calls make JavaScript wait for the GPU. MDN says getError() and getParameter() "cause synchronous stalls on the calling thread". Reading pixels back with readPixels() waits too. Keep them out of the frame loop.
Which GPU does your browser draw with? Press Edit & run:
const gl = document.createElement("canvas").getContext("webgl");
const names = gl?.getExtension("WEBGL_debug_renderer_info");
console.log(names ? gl.getParameter(names.UNMASKED_RENDERER_WEBGL) : "This browser keeps its GPU's name to itself.");- Line 1 makes a canvas and a WebGL context.
- Line 2 asks for the extension that names the GPU. Line 3 prints the name, or a note if the browser hides it.
WebGPU, the newer GPU API
WebGPU is a newer way to use the GPU from a page. Its spec says it "is not related to WebGL". It was designed for today's GPUs. Its explainer says WebGL "doesn't match the design of modern GPUs, causing CPU performance and GPU performance issues."
Two ideas set it apart:
- Record, then send. You write down a frame's commands, then send them together. The explainer says this gives the driver "a larger chunk of work at once".
- More than drawing. It can run general work on the GPU too. Chrome's team calls it "first-class support for general computations on the GPU".
const adapter = await navigator.gpu?.requestAdapter();if (!adapter) throw new Error("No WebGPU here: use WebGL or 2D instead.");const device = await adapter.requestDevice();const ctx = document.querySelector("#steam").getContext("webgpu");ctx.configure({ device, format: navigator.gpu.getPreferredCanvasFormat() });const encoder = device.createCommandEncoder(); // write down this frame's commands// ... a render pass that draws every puff goes here ...device.queue.submit([encoder.finish()]); // send them all at once- Line 1 asks for an adapter: one of the computer's GPUs. Line 2 stops if there isn't one.
- Line 3 asks the adapter for a device, the connection the page works through.
- Lines 4 and 5 connect the canvas to the device.
- Line 6 starts writing down commands. Line 8 sends them all at once.
The course's Chrome found an adapter: vendor apple, architecture metal-3. Chrome 113 brought WebGPU to Windows, macOS and ChromeOS. Safari has it from version 26. Firefox started on Windows, in version 141. So keep a fallback: WebGL or a 2D canvas.
Read the table across: how you draw with each, where the pixels are made, and when to pick it.
| The API | How you draw | Where the pixels are made | When to pick it |
|---|---|---|---|
| 2D canvas | You call one drawing method per shape, from JavaScript. | On the GPU or, for a CPU canvas, on the thread that draws. | Charts, small effects and a few hundred shapes. |
| WebGL | You send data once, then one call draws thousands of shapes with your shaders. | On the GPU. | Thousands of moving things, 3D, and image effects. |
| WebGPU | You record commands, then submit them together. It can also run general work on the GPU. | On the GPU. | New GPU-heavy work, in browsers that support it. |
Which fix does this canvas need?
For each canvas, ask: is the cost in the calls, in the pixels, or in waiting for the main thread?
- The steam stops whenever the page runs other long JavaScript
- Each frame sets a new fillStyle and calls fill() for every one of 500 dots
- A chart redraws all 4,000 dots every frame, though only the cursor line moves
- A full-screen CPU canvas on a 3x phone takes too long to fill each frame
- A star field needs 20,000 moving dots
- Every puff gets shadowBlur on a CPU canvas
Sort each canvas by the fix that helps it most.
Then check where the cost lands. Read the table across: what you change, where its time goes, and what the recording showed.
| What you change | Where the time goes | What the recording showed |
|---|---|---|
| More drawing calls per frame | JavaScript on the thread that draws. | One path took 0.2 ms of JavaScript, one puff at a time took 1.8 ms. |
| Shadows and blurs | Making the pixels: the GPU process, or the main thread on a CPU canvas. | Soft shadows took 20.3 ms a frame on the CPU canvas. |
| A bigger bitmap | Memory, and making the pixels. | The 3x bitmap held 9 times the pixels: 2.1 MB instead of 0.2 MB. |
| Drawing on the main thread | Every frame waits for the main thread. | The steam drew 0 frames during the 400.1 ms ranking code. |
Common mix-ups
- "A canvas animation runs by itself, like a CSS animation." No. Your code draws every frame. On the main thread, Ravi's steam drew 0 frames during the ranking code.
- "If my drawing function is fast, the frame is cheap." No. Soft shadows took the same 1.8 ms of JavaScript as plain circles, and 20.3 ms a frame on a CPU canvas.
- "willReadFrequently: true makes a canvas faster." No. It keeps the canvas on the CPU. Reading gets cheap, but every pixel is then made on the thread that draws.
- "Setting the canvas's CSS width makes it sharper." No. CSS stretches the bitmap. Only the width and height attributes give it more pixels.
- "A sharp canvas on a 3x screen needs 3 times the memory." No. It needs 9 times: 3 times wider and 3 times taller.
- "OffscreenCanvas makes drawing faster." No. The worker draws as fast as before. It just doesn't wait for the main thread.
- "WebGPU is the next version of WebGL." No. Its spec says it "is not related to WebGL". It's a new API, designed for today's GPUs.
Practice exercises
Answer first, then use the hints.
Meera's phone has a device pixel ratio of 2. Ravi sizes the steam canvas for it. What does this code print?
const dpr = 2; // Meera's phone
const width = 380 * dpr;
const height = 150 * dpr;
console.log(`${width * height * 4} bytes`);It prints 912000 bytes, about 0.9 MB. A ratio of 2 gives 4 times the pixels of a 1x bitmap: 2 times wider and 2 times taller.
What does this code print?
const canvas = document.createElement("canvas");
canvas.style.width = "380px";
canvas.style.height = "150px";
console.log(canvas.width, canvas.height);It prints 300 150. That's the HTML standard's default bitmap: 300 by 150. CSS stretches it to 380 by 150 on the screen, so the drawing looks soft.
In the playground, how long was the GPU process busy in one second, with the stamp on the GPU canvas?
38.6 ms. That's more than plain circles needed on the same canvas, 26.8 ms. The main thread's share stayed small: the GPU did the copying.
Ravi moved the sizing after the hand-over. Line 3 throws. What is the name of the error?
const canvas = document.createElement("canvas");
const offscreen = canvas.transferControlToOffscreen();
canvas.width = 380 * 3; // size it for Asha's phone
canvas.height = 150 * 3;const canvas = document.createElement("canvas");
canvas.width = 380 * 3; // size it first
canvas.height = 150 * 3;
const offscreen = canvas.transferControlToOffscreen();
console.log(offscreen.width, offscreen.height);InvalidStateError. Once a canvas is handed over, the page can't resize it. Set the size first, as here, and the OffscreenCanvas starts at 1140 by 450. Or set its width and height in the worker.
Open the course's copy of Ravi's fading steam, which reads its pixels back every frame. What does Chrome's warning in the Console start with?
Canvas2D: Multiple readback operations using getImageData are faster with the willReadFrequently attribute set to true. It's in base_rendering_context_2d.cc, written on the second read when the option wasn't set.
MDN's WebGL best practices warns about one context option, set to false. Which option is it?
alpha: false. MDN says it makes the browser treat the WebGL canvas as opaque, and on some systems that costs a lot. It suggests writing 1.0 for alpha in the shader instead.
Check your understanding
For each question, ask: who draws each frame, and where are the pixels made?
Question 1 of 7What does the second line of Asha's tap example print?
Read the code, then predict// Asha taps Helpful. The steam, and DevTools' Frames track, for 850 ms. const ranking = { startsAt: 151.2, lastsMs: 400.1 }; const steam = { framesDuringRanking: 0, longestGapMs: 413.5 }; const frames = { presented: 28, partiallyPresented: 23 }; console.log(`Ravi's ranking code ran for ${ranking.lastsMs} ms.`); console.log(`The steam drew ${steam.framesDuringRanking} frames in that time.`); console.log(`${frames.partiallyPresented} of ${frames.presented + frames.partiallyPresented} frames were partially presented.`);Choose an answer to see the explanation.
Question 2 of 7Why did the leaf keep swaying while Ravi's steam stopped?
Choose an answer to see the explanation.
Question 3 of 7Ravi's soft shadows took no more JavaScript time than his plain circles. Where did their extra cost show up?
Choose an answer to see the explanation.
Question 4 of 7What does willReadFrequently: true ask the browser to do?
Choose an answer to see the explanation.
Question 5 of 7What does the second line of the bitmap sizes example print?
Read the code, then predict// Ravi's canvas fills 380 by 150 CSS pixels. for (const dpr of [1, 3]) { const width = 380 * dpr; const height = 150 * dpr; const bytes = width * height * 4; // red, green, blue and alpha console.log(`${dpr}x: ${width} by ${height}, ${width * height} pixels, ${(bytes / 1e6).toFixed(1)} MB`); }Choose an answer to see the explanation.
Question 6 of 7Why did the worker's steam keep moving during Ravi's ranking code?
Choose an answer to see the explanation.
Question 7 of 7Why could WebGL draw thousands of puffs with so little main-thread time?
Choose an answer to see the explanation.
Key takeaways
- A canvas shows only what your code draws. On the main thread, a long task stops it, even while CSS animations go on.
- A frame costs JavaScript, to give the drawing commands, and raster, to make the pixels.
- A GPU canvas makes its pixels in the GPU process. A CPU canvas makes them on the thread that draws.
- Fewer calls and fewer colour changes cut the JavaScript. A stamp drawn once cuts the raster.
- willReadFrequently: true makes reading cheap, and drawing slower on the main thread. Use it only when the page reads often.
- A sharp canvas sizes its bitmap by devicePixelRatio. At 3x, that's 9 times the pixels and the memory.
- OffscreenCanvas in a worker keeps an animation moving while the main thread is busy.
- WebGL draws thousands of shapes in one call. WebGPU is the newer API, built for modern GPUs.
Remember the one-liner.
Each canvas frame costs commands and pixels: send few, make few, and draw where the main thread can't block you.
Looking back at Stage 9
This lesson ends Stage 9, Stability and smoothness. In it, you learned to:
- score layout shifts with CLS, find what moved, and stop it moving (Module 30);
- keep style, layout, paint and a big DOM cheap (Module 31);
- keep animations, scrolling, view transitions and canvases smooth, and measure their frames (Module 32).
Sources
The facts on this page come from these specs, docs and source files:
- headless_mode_init.cc: headless Chrome draws WebGL with SwiftShader on Linux, Chromium source.
- HTML Standard: the canvas element, WHATWG.
- html_canvas_element.cc: when a 2D canvas prefers the GPU or the CPU, Chromium source.
- Optimizing canvas, MDN.
- HTML Standard: the will read frequently setting, WHATWG.
- base_rendering_context_2d.cc: what getImageData() does with a GPU canvas, Chromium source.
- base_rendering_context_2d.h: kFallbackToCPUAfterReadbacks, Chromium source.
- CSSOM View: devicePixelRatio, W3C.
- Window: devicePixelRatio property, MDN.
- HTML Standard: the OffscreenCanvas interface, WHATWG.
- HTML Standard: animation frames, in windows and dedicated workers, WHATWG.
- worker_animation_frame_provider.cc: a worker's own frame callbacks, Chromium source.
- begin_frame_provider.cc: the worker's own line to the display compositor, Chromium source.
- OffscreenCanvas: speed up your canvas operations with a web worker, web.dev.
- WebGL best practices, MDN.
- WebGPU, W3C.
- WebGPU Explainer, GPU for the Web Community Group.
- Chrome ships WebGPU, Chrome for Developers.
Coming next: The back/forward cache, the first lesson of Stage 10. You'll make the Back button show the last page at once.