Modely vykreslování: co srovnáváme?
| Kritérium | SVG | Canvas 2D | WebGL 2 | WebGPU |
|---|---|---|---|---|
| Model | Vektorový | Rastrový | GPU grafika | GPU grafika a výpočty |
| DOM pro objekty | Ano, inline | Ne | Ne | Ne |
| Škálování | Vektor kromě bitmap | Překreslit | Znovu vykreslit | Znovu vykreslit |
| Compute shadery | Ne | Ne | Ne (nepřímé techniky) | Ano |
| Složitost | Nízká až střední | Nízká až střední | Vysoká | Vysoká |
| Kompatibilita | Široká | Široká | Široká, závisí na GPU | Závisí na platformě a funkcích |
SVG uchovává vektorový popis ve stromu prvků. Canvas 2D kreslí do bitmapy bez automatického uchování objektů. WebGL a WebGPU také používají canvas, ale mají samostatná API. canvas je HTML prvek, nikoli jediný model akcelerace. [1][2][3][4]
SVG může obsahovat rastrové obrázky; Canvas 2D kreslí vektorové křivky, ale výsledkem je bitmapa. Prohlížeč může obojí akcelerovat pomocí GPU. Získaný kontext má pevný typ; přechod z WebGPU na WebGL vyžaduje jiný canvas. [2][5]
Rastrová scéna vyžaduje vlastní hit testing, například geometrii nebo prostorový index. Čtení ID z GPU bufferu může zvýšit latenci. SVG nabízí hit testing prvků ovlivněný mimo jiné pointer-events.
Retained mode a immediate mode: kdo uchovává stav scény?
| Model | Příklad | Důsledky |
|---|---|---|
| Retained mode | SVG, graf scény Konva | Aktualizace objektů; náklady na paměť a synchronizaci |
| Immediate mode | Canvas 2D bez knihovny | Explicitní kreslení, hit testing a překreslení |
| GPU zdroje a příkazy | WebGL 2, WebGPU | Aplikace spravuje geometrii a zdroje; bez sémantiky objektů |
V retained mode zůstávají objekty a jejich vlastnosti mezi aktualizacemi zachovány. U vloženého SVG spravuje prohlížeč strom elementů; změna atributu mění popis objektu. Canvas 2D mění přímo bitmapu: posun objektu vyžaduje překreslení oblasti, nikoli nutně každého snímku. [1][2]
WebGL a WebGPU uchovávají GPU zdroje, ale nikoli doménové objekty, hierarchii či interakce. Konva a Three.js mohou spravovat graf scény nad rastrovým rendererem. Oddělte dokument, výběr, historii undo a prostorový index od rendereru. [5][20][21]
SVG: škálování, sémantika a interakce
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>
SVG je vhodné pro ikony, diagramy, vektorové mapy a interaktivní grafy. viewBox definuje souřadnice nezávislé na velikosti zobrazení. Inline SVG umožňuje přístup k DOM a CSS; SVG v img neposkytuje rodičovskému dokumentu interaktivní strom. [1]
Mnoho uzlů, změny atributů, filtry a složitá geometrie mohou zvýšit náklady. Seskupování a zjednodušení cest může zabránit migraci na GPU. Trojúhelník má textový popis; interaktivní diagram potřebuje klávesnici a sémantiku.
Canvas 2D: rozlišení a paměťový rozpočet
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();
};
}
Rozměry CSS se liší od bitmapy. Při DPR 2 vyžaduje 800 × 600 CSS pixelů bitmapu 1600 × 1200, čtyřikrát více pixelů než DPR 1. RGBA8 zabere asi 7,32 MiB bez dalších bufferů. Změna width nebo height resetuje kontext; obnovte transformaci a kresbu. [2][6]
Ukázka omezuje počet pixelů a délku strany, kreslí v normalizovaných souřadnicích a odstraňuje observer i listener. Limity jsou rozpočtem aplikace, nikoli zárukou prohlížeče. ResizeObserver a resize pokrývají běžné změny; pro přesné DPR sledujte také hustotu pomocí matchMedia nebo devicePixelContentBoxSize s náhradní variantou. [5][6]
WebGL 2: GPU a správa prostředků
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 nabízí OpenGL ES 3.0, GLSL ES shadery, textury, buffery, instancing a framebuffery. Hodí se pro hry, mapy a 3D. Namísto změn tisíců uzlů DOM připravuje data a příkazy. Náklady ovlivňují draw calls, shadery, textury a počet pixelů. [3][5]
Ukázka vytváří tři vrcholy v shaderu, kontroluje kompilaci a linkování, nastavuje viewport a obnovuje program po webglcontextrestored. Staré prostředky jsou neplatné. preserveDrawingBuffer nepoužívejte standardně kvůli nákladům. Statická bitmapa má pevnou velikost; dynamická scéna vyžaduje překreslení a synchronizaci rozměrů. [5][7]
WebGPU: moderní vykreslování a výpočty
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 zpřístupňuje device, queue, prostředky, bind groups a vykreslovací i výpočetní pipeline. Shadery se obvykle píší v WGSL. Compute shadery podporují paralelní výpočty; malé úlohy, přenosy a čtení zpět mohou výhodu zrušit. [4][8]
Ukázka inicializuje adaptér a zařízení v bezpečném kontextu, vybere formát, asynchronně vytvoří pipeline, zakóduje render pass a odešle příkazy. Řeší chybějící adaptér, chyby validace a ztrátu zařízení, uvolňuje prostředky. Při ztrátě je nutné prostředky obnovit nebo změnit renderer; automatická reinicializace zde není. [4][9]
K 30. 11. 2026 je WebGPU dostupné v hlavních rodinách prohlížečů, ale pokrytí platforem a funkcí se liší. Ověřujte requestAdapter(), requestDevice(), features a limits, nejen navigator.gpu. Implementace a formální stav W3C jsou odlišné. [4][10][11]
Publikace W3C z 16. 11. 2026 uvádí WebGPU jako Candidate Recommendation Draft; také WGSL prochází standardizací. Před requestDevice() ověřte adapter.features a adapter.limits a vyžadujte jen potřebné funkce. [18][19]
Vykreslovací pipeline: WebGL 2 a WebGPU
| Kritérium | WebGL 2 | WebGPU |
|---|---|---|
| Shadery | GLSL ES 3.00 | WGSL |
| Stav | Měnitelný stav kontextu | Pipeline, bind groups, částečně dynamický stav |
| Příkazy | Volání kontextu | Command encoder, pass, command buffer, queue |
| Výpočty | Transform feedback, renderování do textur | Compute pipelines a storage buffery |
| Zdroje | Buffery a textury, vazby závislé na stavu | Explicitní usage flags a layouty |
| Synchronizace | Fences; čtení může blokovat | Queue, mapAsync, pravidla použití zdrojů |
| Chyby | Kompilace, linkování, chyby kontextu | Error scopes, asynchronní chyby, device.lost |
| Volitelné funkce | Rozšíření a limity kontextu | Features a limits adaptéru a zařízení |
Vertex shader určuje pozice v clip space. Rasterizace vytváří fragmenty a interpoluje atributy; fragment shader počítá výstupy, test hloubky a blending ovlivňují render target. Fragment není nutně výsledný pixel (MSAA, překrytí). Compute shadery pracují ve skupinách bez rasterizace. [3][4][8]
WebGL 2 používá měnitelný stav kontextu. WebGPU sdružuje konfiguraci do pipelines a kóduje passy a command buffery. Odeslání do queue neznamená dokončení GPU práce. WebGPU synchronizuje zdroje podle pravidel API, bez ručních bariér typu Vulkan. [3][4][5]
Compute shader bez vykreslování scény
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();
}
}
Příklad zdvojnásobí hodnoty Uint32Array modulo 2^32. Každá invocation zpracuje prvek; kontrola hranice WGSL chrání poslední neúplnou skupinu. Dispatch ceil(N/64), dvě skupiny po 64 pro 65 hodnot. Milion prvků je rozpočet ukázky; ověřují se limity bufferů, bindingů a dispatch. [4][8][22][23]
Nahrajte data do STORAGE s COPY_DST a COPY_SRC, spusťte dispatch a kopírujte do MAP_READ | COPY_DST. Po mapAsync zkopírujte do samostatného pole, zavolejte unmap a uvolněte buffery. Zařízení vlastní operace; sdílené zařízení potřebuje samostatný životní cyklus. Error scopes pokrývají validaci, nedostatek paměti a interní chyby. [4][24]
Nejde o důkaz zrychlení jednoduchého násobení. Porovnejte s CPU pro 0 a 65 prvků i přetečení u32. V produkci znovu používejte zařízení, pipelines a buffery, vyhněte se čtení po každé operaci. Simulace částic a filtry mohou těžit z GPU, pokud to dovolí náklady přenosu.
Výhody, omezení a záruky
| Kritérium | Výhody | Nevýhody | Nezaručuje |
|---|---|---|---|
| SVG | Škálování, DOM a CSS | Náklady uzlů a filtrů | Plnou přístupnost |
| Canvas 2D | Jednoduchá kresba a pixely | Vlastní interakce, paměť bitmapy | Stálý výkon |
| WebGL 2 | Zralé GPU API, 3D ekosystém | Složitý stav, bez compute API | Plynulost a všechna zařízení |
| WebGPU | Explicitní pipeline, compute shadery | Inicializace, kompatibilita, prostředky | Výhodu v každé scéně |
Tabulky uvádějí typické vlastnosti, nikoli benchmarky. Jednoduchá a zřídka aktualizovaná SVG scéna může překonat špatně navržený GPU renderer. Univerzální hranice počtu objektů neexistuje. Rozhoduje zátěž a požadavky produktu. [5][6]
Správa zdrojů a náklady scény
Instancing kreslí společnou geometrii s parametry instancí. Batching seskupuje kompatibilní příkazy, snižuje draw calls a změny stavu. Respektujte blending, pořadí a culling. Zjednodušujte SVG uzly a geometrii; v Canvas 2D zvažte vrstvy a kreslení na vyžádání. [5][6][21]
Do rozpočtu zahrňte buffery, textury, mipmapy, depth/stencil, MSAA a mezivýsledky. RGBA8 textura 4096 × 4096 zabírá 64 MiB v základní úrovni, asi 85,33 MiB s úplnými mipmapami, bez režie a komprese. Nepředpokládejte dostupnost celé VRAM. [5]
Oddělte sdílené a scénové zdroje. Odstraňujte WebGL programy, buffery a textury; ničte nepotřebné WebGPU buffery a textury, zařízení až na konci jeho životního cyklu. Zastavte animace a observery. Po ztrátě kontextu nebo zařízení obnovte zdroje ze scény; důležitá data nesmí existovat pouze na GPU. [5][7][9]
Měření a optimalizace výkonu
Související články POLPROG (anglicky): Critical Rendering Path, Long Tasks, Main Thread and INP.
Při 60 Hz je nominální rozpočet snímku asi 16,67 ms, při 120 Hz 8,33 ms včetně práce prohlížeče. Vedle FPS měřte percentily doby snímku, latenci, inicializaci, paměť a dlouhodobou stabilitu. Srovnávejte stejné scény, bitmapy, DPR, kvalitu a zařízení; oddělte zahřívání shaderů.
Omezte draw calls, změny stavu GPU, zbytečné aktualizace DOM a synchronní čtení GPU. Pro Canvas 2D zvažte vykreslování na vyžádání, cache statických vrstev a OffscreenCanvas. Worker odlehčí hlavní vlákno, ne automaticky GPU; zvažte komunikaci, přenosy a životní cyklus. Měřte INP a Long Tasks. [5][6][12]
Metodika benchmarků
| Metrika | Měření | Úskalí |
|---|---|---|
| Inicializace | Čas do použitelné scény | Oddělit studené a zahřáté běhy |
| Intervaly | Medián, p95, p99, překročení | FPS mohou skrývat záseky |
| CPU a GPU | Profil hlavního vlákna, volitelné GPU dotazy | Submit není dokončení |
| Interakce | Latence ovládání a INP | INP není plynulost animace |
| Paměť a stabilita | Rozpočty, změny scény | Bez přenositelného měření celé VRAM |
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="/cs/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>
Definujte zátěž a kritéria: stejná data, počet objektů, animace, interakce, fyzické rozlišení, srovnatelný antialiasing, obnovovací frekvence, prohlížeč, OS a režim napájení. Oddělte inicializaci a kompilaci shaderů od stabilního běhu. Opakujte ve vyváženém či náhodném pořadí, testujte mobily a teplotu. Nezobecňujte jeden počítač. [5][25]
Kód zahodí 60 intervalů requestAnimationFrame, shromáždí 300 a vypočte medián, p95, p99 a překročení rozpočtu. Nearest rank: pozice ceil(0,95 × N) v seřazeném poli. Intervaly callbacků nejsou čas GPU, prezentované snímky ani INP. Skrytý dokument znamená neplatný běh, platí timeout. Stabilita vyžaduje delší test. [25][26]
WebGL 2: čtěte EXT_disjoint_timer_query_webgl2 asynchronně a zahazujte disjoint výsledky. WebGPU: aktivujte timestamp-query při tvorbě zařízení, pokud je dostupné. performance.now kolem submit měří hlavně odeslání CPU. Interakce a INP měřte zvlášť. [27][28][29]
Přístupnost, bezpečnost a export
Související články POLPROG (anglicky): CSS Animations.
Bitmapa nezpřístupňuje sémantiku objektů. Interaktivní grafy potřebují HTML, klávesnici, popis dat a rovnocennou tabulku. Hry a editory vyžadují focus, přístupné ovládání, omezení pohybu a chybové zprávy. Inline SVG nabízí více možností, ale title a desc nezaručují WCAG. [1][2][13]
Nevkládejte nedůvěryhodné SVG jako surové HTML. Ověřte původ a CSP; pro čtení pixelů Canvas 2D z jiného originu jsou nutné vhodné CORS hlavičky. Kontaminovaná bitmapa blokuje čtení a export. toBlob může vrátit null nebo vyvolat výjimku bez origin-clean. WebGL a WebGPU mají vlastní omezení textur a prostředků. [14][15]
Volba technologie a hybridní architektura
| Scénář | Výchozí volba | Proč |
|---|---|---|
| Ikony, diagramy, běžné grafy | SVG | Sémantika a škálování |
| Fotoeditor, kreslení, jednoduchá 2D hra | Canvas 2D | Přímý přístup k bitmapě |
| 3D mapa, hra, hustá animovaná scéna | WebGL 2 nebo WebGPU | GPU po měření |
| Paralelní simulace, výpočet GPU | WebGPU | Compute shadery |
| Dashboard s mnoha body | Canvas 2D nebo GPU + HTML/SVG | Oddělit grafiku a interakce |
Pro ikony a diagramy začněte SVG, pro kreslení, pixely a jednoduché 2D hry Canvas 2D. Pro 3D a mnoho animovaných objektů vyhodnoťte WebGL 2 a WebGPU na cílových zařízeních. Pro compute shadery a moderní řízení pipeline je WebGPU přirozená volba. Naplánujte náhradu bez hardwarové podpory.
Three.js, Babylon.js, PixiJS a D3 mohou snížit náklady; ověřte renderery, efekty, velikost balíčku a licence. Změna backendu něco stojí. Ovládání HTML, popisky SVG a Canvas/GPU pro hustou scénu se doplňují. Definujte společná data a souřadnice; renderery vyměňujte jen při stejných funkcích.
Three.js WebGPURenderer standardně používá WebGPU a nabízí backend WebGL 2. PixiJS poskytuje více 2D rendererů. Testujte konkrétní efekty a funkce, nikoli předpokládanou shodu backendů. [16][17]
Grafické knihovny a abstrakce
| Knihovna | Použití | Backend a omezení |
|---|---|---|
| Three.js | 3D scény, konfigurátory | WebGLRenderer nebo WebGPURenderer s WebGL 2 backendem; ověřte materiály a postprocessing |
| Babylon.js | 3D hry a aplikace | WebGL a WebGPU; rozdíly funkcí |
| PixiJS | 2D hry, animace, sprity | WebGL/WebGPU a Canvas dle verze; ověřte efekty a stav backendu |
| D3.js | Data, škály, geometrie | SVG nebo Canvas podle implementace |
| Konva.js | Interaktivní 2D editory | Canvas 2D s grafem a vrstvami; další bitmapy a hit testing |
Knihovna může nabídnout graf scény, materiály, batching, události a nástroje pro data. Porovnejte potřebné funkce, backendy, velikost balíčku, údržbu a licenci. D3 je sada vizualizačních nástrojů, nikoli automatický GPU engine. [16][17][20][21][30]
Migrace z WebGL 2 na WebGPU
Zachovejte WebGL 2, pokud pokrývá požadavky a cílová zařízení bez měřitelného přínosu migrace. WebGPU zvažte pro compute, zátěž CPU či nové funkce knihovny; zrychlení není automatické. U nového 3D projektu nejprve zvolte knihovnu a ověřte scénu. [4][5][16][17]
Definujte požadavky a rozpočty; oddělte scénu a interakci; stanovte kontrakty inicializace, vykreslení, resize a uvolnění; ověřte materiály, textury, souřadnice, barvy a efekty; měřte zařízení; nasazujte postupně s fallbackem WebGL 2. Nabídněte CPU variantu nebo oznamte chybějící compute funkce. Neskrývejte významné rozdíly abstrakcí.
Ověřujte adapter, device, features a limits místo user agentu. Neměňte typ kontextu inicializovaného canvas: vytvořte novou plochu, obnovte scénu a události, uvolněte předchozí renderer. Testujte obě varianty včetně chybějící GPU a ztráty zařízení. [2][9][16][31]
Testování a nasazení
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="/cs/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, []);
});
Stejný trojúhelník ukazuje rozdíly API, nejde o benchmark. HTML a CSS jsou oddělené, každý renderer má vlastní plochu; při chybě zůstává SVG a zpráva. Unit testy pokrývají rozpočty, neplatná data a extrémní poměry. V prohlížeči ověřte výsledek, DPR, ztrátu kontextu/zařízení, chybějící GPU a uvolnění prostředků. [5][7][9]
V CI používejte testy logiky a vizuální regrese s tolerancí rasterizace. Pro výkon definujte scénu, akceptační meze a časy snímků na cílovém hardwaru; softwarový renderer nedokazuje výkon hardwaru. Ověřte klávesnici, mobilní zařízení, export a reinicializaci, nejen úspěch.
