Rendering models: what are we actually comparing?
| Criterion | SVG | Canvas 2D | WebGL 2 | WebGPU |
|---|---|---|---|---|
| Model | Vector | Raster | GPU graphics | GPU graphics and compute |
| Object-level DOM | Yes, inline | No | No | No |
| Scaling | Vector except bitmaps | Redraw | Re-render | Re-render |
| Compute shaders | No | No | No (indirect techniques) | Yes |
| Implementation effort | Low–medium | Low–medium | High | High |
| Device compatibility | Broad | Broad | Broad, GPU-dependent | Platform and feature-dependent |
SVG retains a vector description in an element tree. Canvas 2D draws directly into a bitmap without automatically retaining drawn objects. WebGL and WebGPU can use a canvas element too, but expose separate rendering interfaces, not extensions of the 2D context. Canvas is an HTML element, not the name of a single acceleration model. [1][2][3][4]
SVG can include raster images and Canvas 2D can draw vector curves, but the latter's output is a bitmap. Browsers may use GPU acceleration for SVG and Canvas 2D as well. Do not divide the APIs into CPU and GPU categories without measurement. A canvas context has a fixed type once acquired: switching from WebGPU to WebGL requires a separate canvas element. [2][5]
Raster-scene interactions require separate hit testing, for example geometric tests or a spatial index. Reading object IDs from a GPU buffer is also possible but may increase latency. SVG provides browser-level element hit testing, subject to settings such as pointer-events.
Retained mode and immediate mode: who owns scene state?
| Model | Example | Implications |
|---|---|---|
| Retained mode | SVG, Konva scene graph | Object updates; scene storage and synchronization costs |
| Immediate mode | Raw Canvas 2D | Explicit drawing, hit testing and redraw |
| GPU resources and commands | WebGL 2, WebGPU | Application owns geometry, resources and commands; no object semantics |
A retained-mode system keeps scene objects and properties between updates. Inline SVG provides a browser-managed tree: updating an attribute changes an object description rather than individual pixels. Canvas 2D is immediate-mode: drawing changes the bitmap, and moving an object requires redrawing the affected region or scene. It does not require continuous animation. [1][2]
WebGL and WebGPU retain GPU resources but do not provide application objects, parent-child relationships or interaction logic. Libraries such as Konva and Three.js can implement retained scene graphs over raster renderers. Keep document state, selection, undo history and spatial indexes independent of the renderer in an editor. [5][20][21]
SVG: scaling, semantics and interactions
triangle.svg
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 640 360"
role="img"
aria-labelledby="title description"
>
<title id="title">Triangle</title>
<desc id="description">A green triangle on a dark background.</desc>
<rect width="640" height="360" fill="#101827" />
<polygon points="320,72 128,288 512,288" fill="#56d6bd" />
</svg>
Choose SVG for icons, diagrams, vector maps and charts whose individual elements require events or styling. A viewBox defines a logical coordinate system independent of the display size. Inline SVG supports DOM and CSS access; SVG in an img is an image, not an interactive element tree accessible from its parent document. [1]
SVG costs can grow with node count, attribute updates, filters and geometry complexity. Grouping, path simplification and alternative representations may avoid a GPU migration. The triangle below includes a textual description, but an interactive diagram requires keyboard interaction and appropriate semantics as well.
Canvas 2D: bitmap resolution and memory budgets
sizing.ts
export interface BitmapSize {
width: number;
height: number;
scale: number;
}
function requirePositive(value: number): void {
if (!Number.isFinite(value)) {
throw new RangeError("Expected a finite number.");
}
if (value <= 0) {
throw new RangeError("Expected a positive number.");
}
}
export function bitmapSize(
width: number,
height: number,
dpr: number,
maxPixels: number,
maxSide: number,
): BitmapSize {
for (const value of [width, height, dpr, maxPixels, maxSide]) {
requirePositive(value);
}
if (!Number.isSafeInteger(maxPixels)) {
throw new RangeError("Expected an integer pixel budget.");
}
if (!Number.isSafeInteger(maxSide)) {
throw new RangeError("Expected an integer side limit.");
}
const scale = Math.min(
dpr,
Math.sqrt(maxPixels / width / height),
maxSide / width,
maxSide / height,
);
const pixelWidth = Math.max(1, Math.floor(width * scale));
const pixelHeight = Math.max(1, Math.floor(height * scale));
if (pixelWidth * pixelHeight > maxPixels) {
throw new RangeError("Unsupported aspect ratio for this budget.");
}
if (pixelWidth > maxSide) {
throw new RangeError("Width exceeds the side limit.");
}
if (pixelHeight > maxSide) {
throw new RangeError("Height exceeds the side limit.");
}
return { width: pixelWidth, height: pixelHeight, scale };
}
canvas2d.ts
import { bitmapSize } from "./sizing.js";
const MAX_PIXELS = 4_000_000;
const MAX_SIDE = 4_096;
const BACKGROUND = "#101827";
const FOREGROUND = "#56d6bd";
export function mountCanvas(
canvas: HTMLCanvasElement,
onError: (error: unknown) => void = console.warn,
onRestore: () => void = () => {},
): () => void {
const context = canvas.getContext("2d");
if (!context) {
throw new Error("Canvas 2D is unavailable.");
}
const draw = (): void => {
const { width, height } = canvas.getBoundingClientRect();
if (width <= 0 || height <= 0) {
return;
}
const size = bitmapSize(
width,
height,
window.devicePixelRatio,
MAX_PIXELS,
MAX_SIDE,
);
if (canvas.width !== size.width) {
canvas.width = size.width;
}
if (canvas.height !== size.height) {
canvas.height = size.height;
}
context.setTransform(canvas.width, 0, 0, canvas.height, 0, 0);
context.fillStyle = BACKGROUND;
context.fillRect(0, 0, 1, 1);
context.fillStyle = FOREGROUND;
context.beginPath();
context.moveTo(0.5, 0.2);
context.lineTo(0.2, 0.8);
context.lineTo(0.8, 0.8);
context.closePath();
context.fill();
};
const update = (): void => {
try {
draw();
onRestore();
} catch (error) {
onError(error);
}
};
const observer = new ResizeObserver(update);
const controller = new AbortController();
draw();
observer.observe(canvas);
window.addEventListener("resize", update, {
signal: controller.signal,
});
return () => {
observer.disconnect();
controller.abort();
};
}
CSS dimensions and bitmap dimensions differ. At DPR 2, an 800 × 600 CSS pixel surface rendered at full resolution needs a 1600 × 1200 bitmap, four times the pixel count at DPR 1. A single RGBA8 bitmap then occupies about 7.32 MiB before additional buffers. Setting width or height resets the context state; restore the transform and redraw. [2][6]
The example limits pixel count and side length, draws using normalized coordinates and disconnects its observer and listener on disposal. Limits are an illustrative application budget, not guaranteed browser limits. ResizeObserver and resize cover common size changes; applications needing precise DPR tracking should also observe pixel-density changes (e.g. matchMedia or devicePixelContentBoxSize with a fallback). [5][6]
WebGL 2: GPU rendering and resource management
webgl2.ts
const VERTEX = `#version 300 es
void main() {
vec2 points[3] = vec2[3](
vec2(0.0, 0.6), vec2(-0.6, -0.6), vec2(0.6, -0.6)
);
gl_Position = vec4(points[gl_VertexID], 0.0, 1.0);
}`;
const FRAGMENT = `#version 300 es
precision mediump float;
out vec4 color;
void main() {
color = vec4(0.337, 0.839, 0.741, 1.0);
}`;
function compileShader(
gl: WebGL2RenderingContext,
type: number,
source: string,
): WebGLShader {
const shader = gl.createShader(type);
if (!shader) {
throw new Error("Unable to allocate a shader.");
}
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
const message = gl.getShaderInfoLog(shader);
gl.deleteShader(shader);
throw new Error(message ?? "Shader compilation failed.");
}
return shader;
}
function createProgram(gl: WebGL2RenderingContext): WebGLProgram {
const program = gl.createProgram();
if (!program) {
throw new Error("Unable to allocate a program.");
}
const shaders: WebGLShader[] = [];
try {
shaders.push(compileShader(gl, gl.VERTEX_SHADER, VERTEX));
shaders.push(compileShader(gl, gl.FRAGMENT_SHADER, FRAGMENT));
for (const shader of shaders) {
gl.attachShader(program, shader);
}
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
throw new Error(gl.getProgramInfoLog(program) ?? "Link failed.");
}
return program;
} catch (error) {
gl.deleteProgram(program);
throw error;
} finally {
for (const shader of shaders) {
gl.deleteShader(shader);
}
}
}
export function mountWebGL(
canvas: HTMLCanvasElement,
onError: (error: unknown) => void,
onRestore: () => void = () => {},
): () => void {
const gl = canvas.getContext("webgl2");
if (!gl) {
throw new Error("WebGL 2 is unavailable.");
}
const controller = new AbortController();
const options = { signal: controller.signal };
let program: WebGLProgram | undefined;
const draw = (): void => {
program = createProgram(gl);
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.clearColor(0.063, 0.094, 0.153, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.useProgram(program);
gl.drawArrays(gl.TRIANGLES, 0, 3);
};
canvas.addEventListener(
"webglcontextlost",
(event) => {
event.preventDefault();
program = undefined;
onError(new Error("WebGL context lost; waiting for restoration."));
},
options,
);
canvas.addEventListener(
"webglcontextrestored",
() => {
try {
draw();
onRestore();
} catch (error) {
onError(error);
}
},
options,
);
try {
draw();
} catch (error) {
controller.abort();
throw error;
}
return () => {
controller.abort();
if (program) {
gl.useProgram(null);
gl.deleteProgram(program);
}
};
}
WebGL 2 exposes an OpenGL ES 3.0 model, GLSL ES shaders, textures, buffers, instancing and framebuffer rendering. It suits games, maps and complex 3D graphics. Instead of updating thousands of DOM nodes, the application prepares data and rendering commands. Costs depend on draw calls, shaders, texture sizes and pixel count. [3][5]
The example generates three vertex positions in a shader, checks compilation and linking, sets the viewport and rebuilds the program after webglcontextrestored. Resources from the old context are invalid and must be recreated. Avoid using preserveDrawingBuffer by default because it adds costs. This static example uses a fixed bitmap; a dynamic scene needs redraws and size synchronization. [5][7]
WebGPU: modern rendering and compute
gpu-errors.mjs
// Use only on a device owned by this operation, not concurrent callers.
export async function withGpuErrors(device, operation) {
const filters = ["internal", "out-of-memory", "validation"];
const errors = [];
let result;
for (const filter of filters) {
device.pushErrorScope(filter);
}
try {
result = await operation();
} catch (error) {
errors.push(error);
} finally {
for (const filter of filters.toReversed()) {
try {
const error = await device.popErrorScope();
if (error) {
errors.push(new Error(`${filter}: ${error.message}`));
}
} catch (error) {
errors.push(error);
}
}
}
if (errors.length > 0) {
throw new AggregateError(errors, "GPU operation failed.");
}
return result;
}webgpu.mjs
import { withGpuErrors } from "./gpu-errors.mjs";
const SHADER = `
@vertex
fn vertexMain(
@builtin(vertex_index) index: u32
) -> @builtin(position) vec4f {
let points = array<vec2f, 3>(
vec2f(0.0, 0.6), vec2f(-0.6, -0.6), vec2f(0.6, -0.6)
);
return vec4f(points[index], 0.0, 1.0);
}
@fragment
fn fragmentMain() -> @location(0) vec4f {
return vec4f(0.337, 0.839, 0.741, 1.0);
}`;
export async function mountWebGPU(canvas, onError) {
if (!globalThis.isSecureContext) {
throw new Error("WebGPU requires a secure context.");
}
if (!navigator.gpu) {
throw new Error("WebGPU is unavailable.");
}
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) {
throw new Error("No compatible GPU adapter.");
}
const device = await adapter.requestDevice();
let context;
let disposed = false;
const dispose = () => {
if (disposed) {
return;
}
disposed = true;
try {
context?.unconfigure();
} finally {
device.destroy();
}
};
void device.lost.then((info) => {
if (!disposed) {
dispose();
onError(new Error(`GPU device lost: ${info.message}`));
}
});
try {
await withGpuErrors(device, async () => {
context = canvas.getContext("webgpu");
if (!context) {
throw new Error("Cannot create a WebGPU canvas context.");
}
const format = navigator.gpu.getPreferredCanvasFormat();
context.configure({ device, format, alphaMode: "opaque" });
const module = device.createShaderModule({ code: SHADER });
const pipeline = await device.createRenderPipelineAsync({
layout: "auto",
vertex: { module, entryPoint: "vertexMain" },
fragment: {
module,
entryPoint: "fragmentMain",
targets: [{ format }],
},
primitive: { topology: "triangle-list" },
});
if (disposed) {
throw new Error("GPU device was lost during initialization.");
}
const encoder = device.createCommandEncoder();
const pass = encoder.beginRenderPass({
colorAttachments: [
{
view: context.getCurrentTexture().createView(),
clearValue: { r: 0.063, g: 0.094, b: 0.153, a: 1 },
loadOp: "clear",
storeOp: "store",
},
],
});
pass.setPipeline(pipeline);
pass.draw(3);
pass.end();
device.queue.submit([encoder.finish()]);
});
if (disposed) {
throw new Error("GPU device was lost while rendering.");
}
return dispose;
} catch (error) {
dispose();
throw error;
}
}
WebGPU introduces explicit devices, queues, resources, bind groups, render pipelines and compute pipelines. Shader code is typically written in WGSL. Compute shaders support parallel computation without disguising it as rendering. Not every algorithm benefits: small tasks, transfers and readbacks can erase the gains. [4][8]
The example initializes an adapter and device in a secure context, selects a surface format, creates a pipeline asynchronously, encodes a render pass and submits commands. It handles missing adapters, validation errors and device loss and releases resources. A lost device requires rebuilding resources from source data or switching renderers. Automatic reinitialization is not implemented here. [4][9]
Verified on 30 November 2026: WebGPU is available in major browser families, but operating-system and feature coverage remains uneven. Check requestAdapter(), requestDevice(), required features and limits, not just navigator.gpu. Browser implementations and the formal W3C specification status are separate matters. [4][10][11]
The 16 November 2026 W3C publication identifies WebGPU as a Candidate Recommendation Draft; WGSL is also progressing through standardization. Check adapter.features and adapter.limits before requestDevice() and request only capabilities you actually need. [18][19]
Rendering pipeline: WebGL 2 versus WebGPU
| Criterion | WebGL 2 | WebGPU |
|---|---|---|
| Shaders | GLSL ES 3.00 | WGSL |
| Render state | Mutable context state | Pipeline, bind groups and some dynamic state |
| Commands | Context API calls | Command encoder, pass, command buffer, queue |
| Compute | Transform feedback, render-to-texture | Compute pipelines and storage buffers |
| Resources | Buffers and textures, stateful binding | Explicit usage flags and binding layouts |
| Synchronization | Fences; readback may block | Queue, mapAsync and resource usage rules |
| Errors | Compile/link status and context errors | Error scopes, asynchronous errors, device.lost |
| Optional features | Extensions and context limits | Adapter and device features and limits |
A vertex shader processes vertex data and produces clip-space positions. Rasterization generates fragments from primitives and interpolates attributes; fragment shaders compute outputs, while depth testing and blending affect the render target. A fragment is not necessarily a final pixel, for example with MSAA or overlapping geometry. Compute shaders run workgroups without rasterization. [3][4][8]
WebGL 2 uses mutable context state; WebGPU groups configuration in pipelines and explicitly encodes passes and command buffers. Queue submission is not GPU completion. WebGPU handles synchronization and resource transitions according to its API rules rather than exposing Vulkan-style manual barriers. [3][4][5]
Compute shader: computation without rendering a scene
compute-plan.ts
export const WORKGROUP_SIZE = 64;
export const MAX_ELEMENTS = 1_000_000;
export interface ComputeLimits {
maxBufferSize: number;
maxStorageBufferBindingSize: number;
maxComputeWorkgroupsPerDimension: number;
maxComputeWorkgroupSizeX: number;
maxComputeInvocationsPerWorkgroup: number;
}
export function planCompute(length: number, limits: ComputeLimits) {
if (!Number.isSafeInteger(length)) {
throw new RangeError("Expected an integer element count.");
}
if (length < 0 || length > MAX_ELEMENTS) {
throw new RangeError("Element count exceeds the application budget.");
}
const bytes = length * Uint32Array.BYTES_PER_ELEMENT;
const groups = Math.ceil(length / WORKGROUP_SIZE);
if (length === 0) {
return { bytes, groups };
}
if (bytes > limits.maxBufferSize) {
throw new RangeError("Buffer size exceeds the device limit.");
}
if (bytes > limits.maxStorageBufferBindingSize) {
throw new RangeError("Storage binding exceeds the device limit.");
}
if (groups > limits.maxComputeWorkgroupsPerDimension) {
throw new RangeError("Dispatch exceeds the device limit.");
}
if (WORKGROUP_SIZE > limits.maxComputeWorkgroupSizeX) {
throw new RangeError("Workgroup width exceeds the device limit.");
}
if (WORKGROUP_SIZE > limits.maxComputeInvocationsPerWorkgroup) {
throw new RangeError("Too many invocations per workgroup.");
}
return { bytes, groups };
}
export function doubleOnCPU(input: Uint32Array): Uint32Array {
return input.map((value) => value * 2);
}compute.mjs
import {
MAX_ELEMENTS,
WORKGROUP_SIZE,
planCompute,
} from "./dist/compute-plan.js";
import { withGpuErrors } from "./gpu-errors.mjs";
const SHADER = `
@group(0) @binding(0)
var<storage, read_write> values: array<u32>;
@compute @workgroup_size(${WORKGROUP_SIZE})
fn main(@builtin(global_invocation_id) id: vec3u) {
if (id.x >= arrayLength(&values)) {
return;
}
values[id.x] = values[id.x] * 2u;
}`;
async function requestDevice() {
if (!globalThis.isSecureContext || !globalThis.navigator?.gpu) {
throw new Error("WebGPU is unavailable in this context.");
}
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) {
throw new Error("No compatible GPU adapter.");
}
return adapter.requestDevice();
}
async function execute(device, input) {
const { bytes, groups } = planCompute(input.length, device.limits);
let storage;
let readback;
try {
storage = device.createBuffer({
size: bytes,
usage:
GPUBufferUsage.STORAGE |
GPUBufferUsage.COPY_DST |
GPUBufferUsage.COPY_SRC,
});
readback = device.createBuffer({
size: bytes,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(storage, 0, input);
const module = device.createShaderModule({ code: SHADER });
const pipeline = await device.createComputePipelineAsync({
layout: "auto",
compute: { module, entryPoint: "main" },
});
const bindGroup = device.createBindGroup({
layout: pipeline.getBindGroupLayout(0),
entries: [{ binding: 0, resource: { buffer: storage } }],
});
const encoder = device.createCommandEncoder();
const pass = encoder.beginComputePass();
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindGroup);
pass.dispatchWorkgroups(groups);
pass.end();
encoder.copyBufferToBuffer(storage, 0, readback, 0, bytes);
device.queue.submit([encoder.finish()]);
await readback.mapAsync(GPUMapMode.READ);
const mapped = new Uint32Array(readback.getMappedRange());
const result = mapped.slice();
readback.unmap();
return result;
} finally {
readback?.destroy();
storage?.destroy();
}
}
export async function doubleOnGPU(input) {
if (!(input instanceof Uint32Array)) {
throw new TypeError("Expected Uint32Array.");
}
if (input.length > MAX_ELEMENTS) {
throw new RangeError("Input exceeds the application budget.");
}
if (input.length === 0) {
return new Uint32Array();
}
const snapshot = input.slice();
const device = await requestDevice();
try {
return await withGpuErrors(device, () => execute(device, snapshot));
} finally {
device.destroy();
}
}
This example doubles Uint32Array values modulo 2^32. Each shader invocation processes one element; the WGSL bounds check protects the final partial workgroup. Dispatch ceil(N/64) groups: 65 elements need two groups of 64 invocations. One million elements is a demo budget, not a WebGPU limit. The plan checks buffer, storage binding and dispatch limits. [4][8][22][23]
Upload into a STORAGE buffer with COPY_DST and COPY_SRC, dispatch, then copy into a MAP_READ | COPY_DST buffer. Await mapAsync, copy into an independent typed array, unmap and release both buffers. The operation owns its device and destroys it in finally; shared production devices need separate lifecycle management. Error scopes cover validation, out-of-memory and internal errors. [4][24]
This demonstrates the API, not a speedup for trivial multiplication. Compare results with the CPU reference, including zero elements, 65 elements and u32 overflow. In production reuse devices, pipelines and buffers and avoid readback after each operation. Particle simulation, image filters and large arrays are candidates when transfer costs justify GPU processing.
Advantages, limitations and actual guarantees
| Criterion | Pros | Cons | Not guaranteed |
|---|---|---|---|
| SVG | Scaling, DOM and CSS | Many nodes and filters can be costly | Full accessibility |
| Canvas 2D | Simple drawing and pixel operations | Own interaction model, bitmap memory | Constant performance |
| WebGL 2 | Mature GPU API, 3D ecosystem | Complex state, no compute API | Smoothness and universal device support |
| WebGPU | Explicit pipelines, compute shaders | Initialization, compatibility, resource management | Better performance in every scene |
The comparison below describes typical properties, not benchmark results. More objects do not automatically require WebGL: a simple infrequently updated SVG scene may outperform a poorly implemented GPU renderer. There is no universal object-count threshold. Choose based on workload profiles and product requirements. [5][6]
Resource management and scene cost
Instancing draws many instances of shared geometry with different parameters. Batching groups compatible commands, reducing state changes and draw calls. Do not merge objects indiscriminately when blending, draw order or culling differ. For SVG reduce nodes and geometry complexity; for Canvas 2D consider layers and on-demand rendering. [5][6][21]
Budget vertex/index buffers, textures, mipmaps, depth/stencil, MSAA and intermediate targets. A 4096 × 4096 RGBA8 texture takes 64 MiB at its base level, roughly 85.33 MiB with a full mip chain, before overhead or compression. Do not assume all GPU memory is available. Cap resolution, texture sizes and concurrent resources. [5]
Separate shared resources from scene-owned resources. Delete WebGL programs, buffers and textures; destroy unused WebGPU buffers and textures, and destroy a device only when its owner is done. Cancel animation loops and observers on teardown. Recreate resources from scene data after context or device loss; do not keep the sole copy of essential data on the GPU. [5][7][9]
Performance: measurement and optimization
Related POLPROG articles: Critical Rendering Path, Long Tasks, Main Thread and INP.
At 60 Hz the nominal frame budget is about 16.67 ms; at 120 Hz it is about 8.33 ms, including browser work. FPS does not describe the whole experience: measure frame-time percentiles, interaction latency, initialization, memory and sustained stability. Compare identical scenes, bitmap dimensions, DPR, effect quality and devices; separate shader warmup from steady-state rendering.
Reduce draw calls, GPU state changes, unnecessary DOM updates and synchronous GPU readbacks. For Canvas 2D consider on-demand rendering, caching static layers and OffscreenCanvas. Workers can reduce main-thread work but do not automatically reduce GPU work; account for messaging, transfers and lifecycle. Interface performance also includes INP and Long Tasks. [5][6][12]
Benchmark methodology: obtaining comparable results
| Metric | Measure | Pitfall |
|---|---|---|
| Initialization | Time to first usable scene | Separate cold and warm runs |
| Frame intervals | Median, p95, p99, over-budget share | FPS can hide stutter |
| CPU and GPU | Main-thread profiles, optional GPU queries | Submit time is not completion time |
| Interaction | Control latency and page INP | INP is not animation smoothness |
| Memory and stability | Resource budgets, repeated scene changes | No portable total VRAM measurement |
frame-stats.ts
export interface FrameStats {
count: number;
medianMs: number;
p95Ms: number;
p99Ms: number;
maxMs: number;
overBudgetPercent: number;
}
export function summarizeFrames(
intervals: readonly number[],
budgetMs: number,
): FrameStats {
if (!Number.isFinite(budgetMs) || budgetMs <= 0) {
throw new RangeError("Expected a positive frame budget.");
}
if (intervals.length === 0) {
throw new RangeError("At least one interval is required.");
}
for (const interval of intervals) {
if (!Number.isFinite(interval) || interval <= 0) {
throw new RangeError("Expected positive finite intervals.");
}
}
const sorted = [...intervals].sort((a, b) => a - b);
const atIndex = (index: number): number => {
const value = sorted[index];
if (value === undefined) {
throw new RangeError("Invalid sample index.");
}
return value;
};
const percentile = (fraction: number): number => {
return atIndex(Math.ceil(sorted.length * fraction) - 1);
};
const lower = atIndex(Math.floor((sorted.length - 1) / 2));
const upper = atIndex(Math.floor(sorted.length / 2));
const median = lower + (upper - lower) / 2;
const overBudget = intervals.filter((ms) => ms > budgetMs).length;
return {
count: sorted.length,
medianMs: median,
p95Ms: percentile(0.95),
p99Ms: percentile(0.99),
maxMs: percentile(1),
overBudgetPercent: (100 * overBudget) / sorted.length,
};
}frame-probe.ts
import { summarizeFrames, type FrameStats } from "./frame-stats.js";
const WARMUP_FRAMES = 60;
const SAMPLE_FRAMES = 300;
const MAX_DURATION_MS = 30_000;
export function measureFrameIntervals(
render: (timestamp: number) => void,
budgetMs: number,
): Promise<FrameStats> {
return new Promise((resolve, reject) => {
const intervals: number[] = [];
let previous: number | undefined;
let warmup = WARMUP_FRAMES;
let frame = 0;
let timer = 0;
const controller = new AbortController();
const cleanup = (): void => {
cancelAnimationFrame(frame);
window.clearTimeout(timer);
controller.abort();
};
const fail = (error: unknown): void => {
cleanup();
reject(error);
};
const checkVisibility = (): void => {
if (document.hidden) {
fail(new Error("Discard samples from a hidden document."));
}
};
const tick = (timestamp: number): void => {
try {
if (previous !== undefined) {
if (warmup > 0) {
warmup -= 1;
} else {
intervals.push(timestamp - previous);
}
}
if (intervals.length === SAMPLE_FRAMES) {
const stats = summarizeFrames(intervals, budgetMs);
cleanup();
resolve(stats);
return;
}
render(timestamp);
previous = timestamp;
frame = requestAnimationFrame(tick);
} catch (error) {
fail(error);
}
};
if (document.hidden) {
fail(new Error("Run the measurement in a visible document."));
return;
}
document.addEventListener("visibilitychange", checkVisibility, {
signal: controller.signal,
});
timer = window.setTimeout(() => {
fail(new Error("Measurement timed out."));
}, MAX_DURATION_MS);
frame = requestAnimationFrame(tick);
});
}frame-demo.mjs
import { measureFrameIntervals } from "./dist/frame-probe.js";
const canvas = document.querySelector("#probe");
const button = document.querySelector("#measure");
const result = document.querySelector("#result");
if (!(canvas instanceof HTMLCanvasElement)) {
throw new Error("Missing canvas.");
}
if (!(button instanceof HTMLButtonElement)) {
throw new Error("Missing measurement button.");
}
if (!result) {
throw new Error("Missing measurement output.");
}
const context = canvas.getContext("2d");
if (!context) {
throw new Error("Canvas 2D unavailable.");
}
const BUDGET_MS = 1000 / 60;
const SIDE = 32;
function render(timestamp) {
const x = (timestamp / 5) % (canvas.width - SIDE);
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(x, 100, SIDE, SIDE);
}
button.addEventListener("click", async () => {
button.disabled = true;
result.textContent = "Measuring…";
try {
const stats = await measureFrameIntervals(render, BUDGET_MS);
result.textContent = JSON.stringify(stats, null, 2);
} catch (error) {
result.textContent = "Measurement failed. Repeat in a visible tab.";
console.warn(error);
} finally {
button.disabled = false;
}
});frame-demo.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Frame interval probe</title>
<link rel="stylesheet" href="/en/styles.css" />
<script type="module" src="frame-demo.mjs"></script>
</head>
<body>
<main>
<h1>Frame interval probe</h1>
<p>Example workload only. Not a renderer comparison.</p>
<canvas
id="probe"
width="640"
height="360"
role="img"
aria-label="Moving square"
></canvas>
<button id="measure" type="button">Measure frame intervals</button>
<pre id="result" role="status"></pre>
</main>
</body>
</html>
Define a workload and acceptance criteria first. Use the same data, object count, animation and interaction, physical bitmap resolution, comparable antialiasing, refresh rate, browser, OS and power mode. Separate initialization and shader compilation from steady-state performance. Repeat runs in balanced or randomized order, test mobile and thermal behavior, and avoid generalizing results from one machine. [5][25]
The example discards 60 warm-up requestAnimationFrame intervals, collects 300, and calculates median, p95, p99 and the percentage over budget. Nearest-rank p95 is the sorted item at ceil(0.95 × N). These are callback intervals, not GPU execution time, actual presented frames or INP. It rejects hidden-document runs and times out. Use longer runs for stability and thermal testing. [25][26]
WebGL 2 can use EXT_disjoint_timer_query_webgl2 where available; poll asynchronously and discard disjoint results. WebGPU has optional timestamp-query, which must be enabled on device creation. Timing submit with performance.now mainly measures CPU submission, not GPU completion. Measure user interaction and page INP separately. [27][28][29]
Accessibility, security and export
Related POLPROG articles: CSS Animations.
A bitmap does not automatically expose the semantics of drawn objects. For interactive charts provide HTML with keyboard navigation, data descriptions and an equivalent table. For games and editors manage focus, accessible controls, reduced motion and clear error messages. Inline SVG offers more semantic options, but title and desc alone do not guarantee WCAG conformance. [1][2][13]
Do not insert untrusted SVG as raw HTML. Verify asset provenance and CSP; cross-origin images require appropriate CORS headers if Canvas 2D pixels will be read. A tainted bitmap blocks pixel reads and export. toBlob can return null or throw if the bitmap is not origin-clean. WebGL and WebGPU have their own texture-source and resource constraints. [14][15]
Technology selection and hybrid architecture
| Scenario | Starting point | Why |
|---|---|---|
| Icons, diagrams, conventional charts | SVG | Semantics and scaling |
| Photo editor, sketchpad, simple 2D game | Canvas 2D | Direct bitmap access |
| 3D map, game, dense animated scene | WebGL 2 or WebGPU | GPU rendering after measurement |
| Parallel simulation, GPU computation | WebGPU | Compute shaders |
| Analytics dashboard with many points | Canvas 2D or GPU + HTML/SVG | Separate graphics from interactions |
Start with SVG for icons, diagrams and conventional charts; consider Canvas 2D for drawing, pixel editing and simple 2D games. For 3D scenes and many animated objects, evaluate WebGL 2 and WebGPU on target devices. If compute shaders or modern pipeline control are required, WebGPU is a natural candidate. Public applications need a fallback when hardware support is missing.
Libraries such as Three.js, Babylon.js, PixiJS and D3 can reduce implementation effort; examine supported renderers, effect compatibility, bundle size and licensing. Do not assume switching a library backend is free. HTML controls, SVG labels and a Canvas/GPU dense scene often form a practical combination. Establish a shared data and coordinate model; treat renderers as interchangeable adapters only where they actually preserve the same capabilities.
Three.js WebGPURenderer defaults to WebGPU and provides a WebGL 2 backend. PixiJS offers multiple 2D renderers. In either case, test the effects and features you actually use rather than assuming backend parity. [16][17]
Graphics libraries: selecting an abstraction
| Library | Typical use | Backend and limitations |
|---|---|---|
| Three.js | 3D scenes, visualizations, configurators | WebGLRenderer or WebGPURenderer with WebGL 2 backend; verify materials and post-processing |
| Babylon.js | Games, 3D applications, comprehensive engine | WebGL and WebGPU; backend-specific feature differences |
| PixiJS | 2D games, animation, many sprites | WebGL/WebGPU and version-dependent Canvas support; verify effects and backend status |
| D3.js | Data visualization, scales, geometry | SVG or Canvas; application chooses renderer |
| Konva.js | 2D editors, object interaction | Canvas 2D scene graph and layers; extra bitmaps and hit-testing costs |
Not every project needs a custom renderer. Libraries may provide scene graphs, materials, batching, events or data utilities. Compare actual required features, supported backends, bundle size, maintenance and licensing. D3 is a data visualization toolbox, not an automatic GPU rendering engine. [16][17][20][21][30]
Migrating from WebGL 2 to WebGPU without a forced rewrite
Keep WebGL 2 when it meets requirements on target devices and migration offers no measured benefit. Consider WebGPU for required compute shaders, rendering-related CPU overhead or new library features. A new backend does not inherently improve performance. For new 3D products choose the library and assess scene compatibility first. [4][5][16][17]
Define requirements and budgets; separate scene state and interaction logic; agree on initialization, rendering, resize and disposal contracts; test materials, textures, coordinates, colors and effects; benchmark target devices; roll out gradually with a WebGL 2 fallback. Provide a separate CPU implementation or disclose unavailable compute-only features. Avoid a common abstraction that hides important feature differences.
Check the adapter, device, required features and limits instead of user-agent detection. Do not change the context type of an initialized canvas: create a fresh surface, restore scene state, rebind events and dispose of the previous renderer. A library fallback does not guarantee identical effects. Test both paths, including unavailable GPU and device loss. [2][9][16][31]
Testing and deployment
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Graphics API comparison</title>
<link rel="stylesheet" href="/en/styles.css" />
<script type="module" src="main.mjs"></script>
<script type="module" src="compute-demo.mjs"></script>
</head>
<body>
<main>
<h1>Four rendering models</h1>
<p>Every example draws the same green triangle.</p>
<section aria-labelledby="svg-heading">
<h2 id="svg-heading">SVG</h2>
<img src="triangle.svg" alt="Green triangle" />
</section>
<section aria-labelledby="canvas-heading">
<h2 id="canvas-heading">Canvas 2D</h2>
<canvas
id="canvas2d"
width="640"
height="360"
role="img"
aria-label="Green triangle"
></canvas>
<p id="canvas2d-status" role="status"></p>
</section>
<section aria-labelledby="gl-heading">
<h2 id="gl-heading">WebGL 2</h2>
<canvas
id="webgl"
width="640"
height="360"
role="img"
aria-label="Green triangle"
></canvas>
<p id="webgl-status" role="status"></p>
</section>
<section aria-labelledby="gpu-heading">
<h2 id="gpu-heading">WebGPU</h2>
<canvas
id="webgpu"
width="640"
height="360"
role="img"
aria-label="Green triangle"
></canvas>
<p id="webgpu-status" role="status"></p>
</section>
<section aria-labelledby="compute-heading">
<h2 id="compute-heading">Parallel compute</h2>
<p>Double five unsigned integers. This is not a benchmark.</p>
<button type="button" id="compute-cpu">Run on CPU</button>
<button type="button" id="compute-gpu">Run on GPU</button>
<p id="compute-status" role="status"></p>
</section>
</main>
</body>
</html>
styles.css
body {
margin: 2rem auto;
max-width: 45rem;
padding: 0 1rem;
font-family: system-ui, sans-serif;
color: #101827;
background: #f8fafc;
}
canvas,
img {
display: block;
width: 100%;
height: auto;
aspect-ratio: 16 / 9;
}
[hidden] {
display: none;
}
main.mjs
import { mountCanvas } from "./dist/canvas2d.js";
import { mountWebGL } from "./dist/webgl2.js";
import { mountWebGPU } from "./webgpu.mjs";
const cleanups = [];
let disposed = false;
async function start(id, mount) {
const canvas = document.getElementById(id);
const status = document.getElementById(`${id}-status`);
if (!(canvas instanceof HTMLCanvasElement)) {
throw new Error(`Missing canvas: ${id}`);
}
if (!status) {
throw new Error(`Missing status: ${id}`);
}
const report = (error) => {
if (disposed) {
return;
}
// Preserve the Canvas 2D surface so resizing can recover it.
canvas.hidden = id !== "canvas2d";
status.textContent = "Renderer unavailable. See the SVG example.";
console.warn(error);
};
try {
const restore = () => {
if (disposed) {
return;
}
canvas.hidden = false;
status.textContent = "";
};
const cleanup = await mount(canvas, report, restore);
if (disposed) {
cleanup();
return;
}
cleanups.push(cleanup);
} catch (error) {
report(error);
}
}
window.addEventListener("pagehide", (event) => {
if (event.persisted) {
return;
}
disposed = true;
for (const cleanup of cleanups.splice(0)) {
cleanup();
}
});
await Promise.all([
start("canvas2d", mountCanvas),
start("webgl", mountWebGL),
start("webgpu", mountWebGPU),
]);
sizing.test.mjs
import assert from "node:assert/strict";
import { test } from "node:test";
import { bitmapSize } from "./dist/sizing.js";
const limits = [4_000_000, 4_096];
test("uses the display pixel ratio within the budget", () => {
// Given
const width = 640;
const height = 360;
// When
const result = bitmapSize(width, height, 2, ...limits);
// Then
assert.deepEqual(result, { width: 1280, height: 720, scale: 2 });
});
test("limits the total pixel count", () => {
const result = bitmapSize(1000, 1000, 3, ...limits);
assert.equal(result.width, 2000);
assert.equal(result.height, 2000);
});
test("limits the dimensions independently", () => {
const result = bitmapSize(6000, 100, 1, ...limits);
assert.equal(result.width, 4096);
});
for (const invalid of [0, -1, NaN, Infinity]) {
test(`rejects invalid width: ${invalid}`, () => {
assert.throws(() => bitmapSize(invalid, 100, 1, ...limits));
});
}
test("rejects a fractional pixel budget", () => {
assert.throws(() => bitmapSize(100, 100, 1, 1.5, 100));
});
test("rejects a fractional maximum dimension", () => {
assert.throws(() => bitmapSize(100, 100, 1, 100, 1.5));
});
test("rejects extreme aspect ratios outside the budget", () => {
assert.throws(() => bitmapSize(1e12, 1, 1, 10, 4096));
});
tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"lib": ["ES2022", "DOM"],
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"outDir": "dist"
},
"include": ["*.ts"]
}compute-demo.mjs
import { doubleOnCPU } from "./dist/compute-plan.js";
import { doubleOnGPU } from "./compute.mjs";
const cpuButton = document.querySelector("#compute-cpu");
const gpuButton = document.querySelector("#compute-gpu");
const status = document.querySelector("#compute-status");
if (!(cpuButton instanceof HTMLButtonElement)) {
throw new Error("Missing CPU button.");
}
if (!(gpuButton instanceof HTMLButtonElement)) {
throw new Error("Missing GPU button.");
}
if (!status) {
throw new Error("Missing compute status.");
}
async function run(compute, label) {
cpuButton.disabled = true;
gpuButton.disabled = true;
status.textContent = `${label}: calculating…`;
try {
const input = new Uint32Array([1, 2, 3, 4, 5]);
const result = await compute(input);
status.textContent = `${label}: ${result.join(", ")}`;
} catch (error) {
status.textContent = `${label} failed. Try the CPU example.`;
console.warn(error);
} finally {
cpuButton.disabled = false;
gpuButton.disabled = false;
}
}
cpuButton.addEventListener("click", () => {
void run(doubleOnCPU, "CPU");
});
gpuButton.addEventListener("click", () => {
void run(doubleOnGPU, "GPU");
});advanced.test.mjs
import assert from "node:assert/strict";
import { test } from "node:test";
import { planCompute, doubleOnCPU } from "./dist/compute-plan.js";
import { summarizeFrames } from "./dist/frame-stats.js";
import { doubleOnGPU } from "./compute.mjs";
const limits = {
maxBufferSize: 4_000_000,
maxStorageBufferBindingSize: 4_000_000,
maxComputeWorkgroupsPerDimension: 65_535,
maxComputeWorkgroupSizeX: 256,
maxComputeInvocationsPerWorkgroup: 256,
};
test("dispatch rounds up a partial workgroup", () => {
// Given
const length = 65;
// When
const plan = planCompute(length, limits);
// Then
assert.deepEqual(plan, { bytes: 260, groups: 2 });
});
test("empty input requires no dispatch", () => {
// Given / When
const plan = planCompute(0, limits);
// Then
assert.deepEqual(plan, { bytes: 0, groups: 0 });
});
for (const length of [-1, 0.5, NaN, Infinity, 1_000_001]) {
test(`rejects invalid element count ${length}`, () => {
// Given / When / Then
assert.throws(() => planCompute(length, limits), RangeError);
});
}
for (const key of Object.keys(limits)) {
test(`rejects insufficient ${key}`, () => {
// Given
const restricted = { ...limits, [key]: 1 };
// When / Then
assert.throws(() => planCompute(65, restricted), RangeError);
});
}
test("CPU reference preserves input and wraps unsigned integers", () => {
// Given
const input = new Uint32Array([0, 1, 0xffffffff, 0x80000000]);
// When
const result = doubleOnCPU(input);
// Then
assert.deepEqual([...result], [0, 2, 0xfffffffe, 0]);
assert.deepEqual([...input], [0, 1, 0xffffffff, 0x80000000]);
});
test("GPU entry point accepts empty input without a device", async () => {
// Given / When
const result = await doubleOnGPU(new Uint32Array());
// Then
assert.deepEqual(result, new Uint32Array());
});
test("GPU entry point rejects the wrong input type", async () => {
// Given / When / Then
await assert.rejects(doubleOnGPU([1, 2]), TypeError);
});
test("GPU entry point rejects oversized input", async () => {
// Given
const input = new Uint32Array(1_000_001);
// When / Then
await assert.rejects(doubleOnGPU(input), RangeError);
});
test("frame statistics use nearest-rank percentiles", () => {
// Given
const intervals = [40, 10, 20, 10];
// When
const result = summarizeFrames(intervals, 20);
// Then
assert.deepEqual(result, {
count: 4,
medianMs: 15,
p95Ms: 40,
p99Ms: 40,
maxMs: 40,
overBudgetPercent: 25,
});
assert.deepEqual(intervals, [40, 10, 20, 10]);
});
for (const intervals of [[], [0], [NaN], [Infinity], [-1]]) {
test(`rejects invalid samples ${intervals}`, () => {
// Given / When / Then
assert.throws(() => summarizeFrames(intervals, 16), RangeError);
});
}
test("rejects an invalid frame budget", () => {
// Given / When / Then
assert.throws(() => summarizeFrames([10], 0), RangeError);
});
// These test error-scope orchestration, not an actual GPU driver.
const { withGpuErrors } = await import("./gpu-errors.mjs");
function mockScopes(validationError = null) {
const scopes = [];
const events = [];
const device = {
pushErrorScope(filter) {
scopes.push(filter);
events.push(`push:${filter}`);
},
async popErrorScope() {
const filter = scopes.pop();
events.push(`pop:${filter}`);
return filter === "validation" ? validationError : null;
},
};
return { device, scopes, events };
}
test("GPU error scopes are closed in reverse order", async () => {
// Given
const { device, scopes, events } = mockScopes();
// When
const result = await withGpuErrors(device, async () => 42);
// Then
assert.equal(result, 42);
assert.deepEqual(scopes, []);
assert.deepEqual(events, [
"push:internal",
"push:out-of-memory",
"push:validation",
"pop:validation",
"pop:out-of-memory",
"pop:internal",
]);
});
test("GPU scope errors and operation errors are preserved", async () => {
// Given
const { device, scopes } = mockScopes({ message: "Invalid binding" });
const original = new Error("Readback failed");
// When / Then
await assert.rejects(
withGpuErrors(device, async () => {
throw original;
}),
(error) => {
assert.ok(error instanceof AggregateError);
assert.equal(error.errors[0], original);
assert.match(error.errors[1].message, /Invalid binding/);
return true;
},
);
assert.deepEqual(scopes, []);
});
The shared example renders the same triangle, demonstrating API differences rather than benchmarking. HTML and CSS are separated from code. Each renderer has its own surface; if initialization fails, the SVG example and an error message remain available. Unit tests cover bitmap budgets, invalid input and extreme aspect ratios. Browser tests should also cover actual output, DPR changes, WebGL context loss, WebGPU device loss, unavailable GPU and resource cleanup. [5][7][9]
In CI, use logic tests and visual regression tests with tolerance for rasterization differences. Target-hardware performance tests need a defined scene, acceptance thresholds and frame-time measurements; software-renderer results do not prove hardware performance. Before release, check keyboard accessibility, mobile devices, data export and reinitialization. Test more than the success path.
