Prejsť na obsah

Hľadať

Články, nástroje, riešenia a materiály z databázy znalostí

Začnite písať pre vyhľadávanie článkov, nástrojov a aplikácií.

Canvas vs SVG vs WebGL vs WebGPU: ktorú grafickú technológiu vybrať?

Výber závisí od scény, interakcií, rozlíšenia a cieľových zariadení. Obchodný graf, editor fotografií a herný engine majú odlišné požiadavky. Sprievodca porovnáva štyri modely vykresľovania bez zbytočnej zložitosti.

Publikované Autor Čas čítania 27 min čítania
Na tejto stránke Obsah: rýchla navigácia medzi časťami

Modely vykresľovania: čo porovnávame?

Canvas vs SVG vs WebGL vs WebGPU
KritériumSVGCanvas 2DWebGL 2WebGPU
ModelVektorovýRastrovýGPU grafikaGPU grafika a výpočty
DOM pre objektyÁno, inlineNieNieNie
ŠkálovanieVektor okrem bitmapyPrekresliťZnovu vykresliťZnovu vykresliť
Compute shaderyNieNieNie (nepriame techniky)Áno
ZložitosťNízka až strednáNízka až strednáVysokáVysoká
KompatibilitaŠirokáŠirokáŠiroká, závisí od GPUZávisí od platformy a funkcií

SVG uchováva vektorový opis v strome prvkov. Canvas 2D kreslí do bitmapy bez automatického uchovania objektov. WebGL a WebGPU tiež používajú canvas, ale majú samostatné API. canvas je HTML prvok, nie jediný model akcelerácie. [1][2][3][4]

SVG môže obsahovať rastrové obrázky; Canvas 2D kreslí vektorové krivky, ale výsledkom je bitmapa. Prehliadač môže obe technológie akcelerovať GPU. Získaný kontext má pevný typ; prechod z WebGPU na WebGL vyžaduje iný canvas. [2][5]

Rastrová scéna potrebuje vlastný hit testing, napríklad geometriu alebo priestorový index. Čítanie ID z GPU bufferu môže zvýšiť latenciu. SVG ponúka hit testing prvkov ovplyvnený aj pointer-events.

Retained mode a immediate mode: kto uchováva stav scény?

Retained mode a immediate mode: kto uchováva stav scény?
ModelPríkladDôsledky
Retained modeSVG, graf scény KonvaAktualizácia objektov; náklady na pamäť a synchronizáciu
Immediate modeCanvas 2D bez knižniceExplicitné kreslenie, hit testing a prekreslenie
GPU zdroje a príkazyWebGL 2, WebGPUAplikácia spravuje geometriu a zdroje; bez sémantiky objektov

V retained mode zostávajú objekty a ich vlastnosti medzi aktualizáciami zachované. Pri vloženom SVG prehliadač spravuje strom elementov; zmena atribútu mení opis objektu. Canvas 2D mení priamo bitmapu: posun objektu vyžaduje prekreslenie oblasti, nie nevyhnutne každého snímku. [1][2]

WebGL a WebGPU uchovávajú GPU zdroje, ale nie doménové objekty, hierarchiu či interakcie. Konva a Three.js môžu spravovať graf scény nad rastrovým rendererom. Oddeľte dokument, výber, históriu undo a priestorový index od renderera. [5][20][21]

SVG: škálovanie, sémantika a interakcie

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é na ikony, diagramy, vektorové mapy a interaktívne grafy. viewBox definuje súradnice nezávislé od veľkosti zobrazenia. Inline SVG umožňuje prístup k DOM a CSS; SVG v img neposkytuje nadradenému dokumentu interaktívny strom. [1]

Veľa uzlov, zmeny atribútov, filtre a zložitá geometria môžu zvýšiť náklady. Zoskupenie a zjednodušenie ciest môže predísť migrácii na GPU. Trojuholník má textový opis; interaktívny diagram potrebuje aj klávesnicu a sémantiku.

Canvas 2D: rozlíšenie 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();
  };
}

Rozmery CSS sa líšia od bitmapy. Pri DPR 2 vyžaduje 800 × 600 CSS pixelov bitmapu 1600 × 1200, štvornásobok DPR 1. RGBA8 zaberie asi 7,32 MiB bez ďalších bufferov. Zmena width alebo height resetuje kontext; obnovte transformáciu a kresbu. [2][6]

Ukážka obmedzuje počet pixelov a dĺžku strany, kreslí v normalizovaných súradniciach a odstraňuje observer aj listener. Limity sú rozpočet aplikácie, nie záruka prehliadača. ResizeObserver a resize pokrývajú bežné zmeny; na presné DPR sledujte aj hustotu pomocou matchMedia alebo devicePixelContentBoxSize s náhradným riešením. [5][6]

WebGL 2: GPU a správa prostriedkov

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 poskytuje OpenGL ES 3.0, GLSL ES shadery, textúry, buffery, instancing a framebuffery. Hodí sa na hry, mapy a 3D. Namiesto zmeny tisícov DOM uzlov pripravuje údaje a príkazy. Náklady ovplyvňujú draw calls, shadery, textúry a pixely. [3][5]

Ukážka vytvára tri vrcholy v shaderi, kontroluje kompiláciu a linkovanie, nastavuje viewport a obnovuje program po webglcontextrestored. Staré prostriedky sú neplatné. preserveDrawingBuffer nepoužívajte predvolene pre jeho náklady. Statická bitmapa má pevnú veľkosť; dynamická scéna vyžaduje prekreslenie a synchronizáciu rozmerov. [5][7]

WebGPU: moderné vykresľovanie 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 explicitne poskytuje device, queue, prostriedky, bind groups a vykresľovacie i výpočtové pipeline. Shadery sa zvyčajne píšu v WGSL. Compute shadery podporujú paralelné výpočty; malé úlohy, prenosy a spätné čítanie môžu výhodu zrušiť. [4][8]

Ukážka inicializuje adaptér a zariadenie v bezpečnom kontexte, vyberá formát, asynchrónne vytvára pipeline, kóduje render pass a odosiela príkazy. Rieši chýbajúci adaptér, chyby validácie a stratu zariadenia, uvoľňuje prostriedky. Pri strate obnovte prostriedky alebo zmeňte renderer; automatická reinicializácia tu nie je. [4][9]

K 30. 11. 2026 je WebGPU dostupné v hlavných rodinách prehliadačov, no pokrytie platforiem a funkcií sa líši. Overujte requestAdapter(), requestDevice(), features a limits, nielen navigator.gpu. Implementácia a formálny stav W3C sú odlišné. [4][10][11]

Publikácia W3C zo 16. 11. 2026 uvádza WebGPU ako Candidate Recommendation Draft; aj WGSL prechádza štandardizáciou. Pred requestDevice() overte adapter.features a adapter.limits a vyžadujte len potrebné funkcie. [18][19]

Vykresľovacia pipeline: WebGL 2 a WebGPU

Vykresľovacia pipeline: WebGL 2 a WebGPU
KritériumWebGL 2WebGPU
ShaderyGLSL ES 3.00WGSL
StavMeniteľný stav kontextuPipeline, bind groups, čiastočne dynamický stav
PríkazyVolania kontextuCommand encoder, pass, command buffer, queue
VýpočtyTransform feedback, renderovanie do textúrCompute pipelines a storage buffery
ZdrojeBuffery a textúry, väzby závislé od stavuExplicitné usage flags a layouty
SynchronizáciaFences; čítanie môže blokovaťQueue, mapAsync, pravidlá použitia zdrojov
ChybyKompilácia, linkovanie, chyby kontextuError scopes, asynchrónne chyby, device.lost
Voliteľné funkcieRozšírenia a limity kontextuFeatures a limits adaptéra a zariadenia

Vertex shader určuje pozície v clip space. Rasterizácia vytvára fragmenty a interpoluje atribúty; fragment shader počíta výstupy, test hĺbky a blending ovplyvňujú render target. Fragment nemusí byť výsledným pixelom (MSAA, prekrytie). Compute shadery pracujú v skupinách bez rasterizácie. [3][4][8]

WebGL 2 používa meniteľný stav kontextu. WebGPU zoskupuje konfiguráciu do pipelines a kóduje passy a command buffery. Odoslanie do queue neznamená dokončenie práce GPU. WebGPU synchronizuje zdroje podľa pravidiel API, bez ručných bariér typu Vulkan. [3][4][5]

Compute shader bez vykresľovania 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();
  }
}

Príklad zdvojnásobí hodnoty Uint32Array modulo 2^32. Každá invocation spracuje prvok; kontrola hranice WGSL chráni poslednú neúplnú skupinu. Dispatch ceil(N/64), dve skupiny po 64 pre 65 hodnôt. Milión prvkov je rozpočet ukážky; kontrolujú sa limity bufferov, bindingov a dispatchu. [4][8][22][23]

Nahrajte dáta do STORAGE s COPY_DST a COPY_SRC, spustite dispatch a kopírujte do MAP_READ | COPY_DST. Po mapAsync skopírujte do samostatného poľa, zavolajte unmap a uvoľnite buffery. Zariadenie vlastní operácia; zdieľané zariadenie potrebuje samostatný životný cyklus. Error scopes pokrývajú validáciu, nedostatok pamäte a interné chyby. [4][24]

Nejde o dôkaz zrýchlenia jednoduchého násobenia. Porovnajte s CPU pre 0 a 65 prvkov aj pretečenie u32. V produkcii opakovane používajte zariadenia, pipelines a buffery; vyhnite sa čítaniu po každej operácii. Simulácie častíc a filtre môžu využiť GPU, ak to umožnia náklady prenosu.

Výhody, obmedzenia a záruky

Výhody, obmedzenia a záruky
KritériumVýhodyNevýhodyNezaručuje
SVGŠkálovanie, DOM a CSSNáklady uzlov a filtrovPlnú prístupnosť
Canvas 2DJednoduchá kresba a pixelyVlastná interakcia, pamäť bitmapyStály výkon
WebGL 2Zrelé GPU API, 3D ekosystémZložitý stav, bez compute APIPlynulosť a všetky zariadenia
WebGPUExplicitné pipeline, compute shaderyInicializácia, kompatibilita, prostriedkyVýhodu v každej scéne

Tabuľky uvádzajú typické vlastnosti, nie benchmarky. Jednoduchá, zriedka aktualizovaná SVG scéna môže prekonať zle navrhnutý GPU renderer. Univerzálna hranica počtu objektov neexistuje. Rozhoduje záťaž a požiadavky produktu. [5][6]

Správa zdrojov a náklady scény

Instancing kreslí spoločnú geometriu s parametrami inštancií. Batching zoskupuje kompatibilné príkazy a znižuje draw calls a zmeny stavu. Zohľadnite blending, poradie a culling. Zjednodušujte SVG uzly a geometriu; pri Canvas 2D zvážte vrstvy a kreslenie na vyžiadanie. [5][6][21]

Do rozpočtu zahrňte buffery, textúry, mipmapy, depth/stencil, MSAA a medzivýsledky. RGBA8 textúra 4096 × 4096 zaberá 64 MiB v základnej úrovni, asi 85,33 MiB s úplnými mipmapami, bez réžie a kompresie. Nepredpokladajte dostupnosť celej VRAM. [5]

Oddeľte zdieľané a scénové zdroje. Odstraňujte WebGL programy, buffery a textúry; ničte nepotrebné WebGPU buffery a textúry, zariadenie až na konci jeho životného cyklu. Zastavte animácie a observery. Po strate kontextu alebo zariadenia obnovte zdroje zo scény; dôležité dáta nesmú existovať len na GPU. [5][7][9]

Meranie a optimalizácia výkonu

Súvisiace články POLPROG (anglicky): Critical Rendering Path, Long Tasks, Main Thread and INP.

Pri 60 Hz je nominálny rozpočet snímky asi 16,67 ms, pri 120 Hz 8,33 ms vrátane práce prehliadača. Okrem FPS merajte percentily času snímky, latenciu, inicializáciu, pamäť a stabilitu. Porovnávajte rovnaké scény, bitmapy, DPR, kvalitu a zariadenia; zahrievanie shaderov merajte oddelene.

Obmedzte draw calls, zmeny stavu GPU, zbytočné aktualizácie DOM a synchronné čítanie GPU. Pri Canvas 2D zvážte vykresľovanie na požiadanie, cache statických vrstiev a OffscreenCanvas. Worker odľahčí hlavné vlákno, nie automaticky GPU; zvážte komunikáciu, prenosy a životný cyklus. Merajte aj INP a Long Tasks. [5][6][12]

Metodika benchmarkov

Metodika benchmarkov
MetrikaMeranieÚskalie
InicializáciaČas do použiteľnej scényOddeliť studené a zahriate behy
IntervalyMedián, p95, p99, prekročeniaFPS môžu skrývať trhanie
CPU a GPUProfil hlavného vlákna, voliteľné GPU dotazySubmit nie je dokončenie
InterakcieLatencia ovládania a INPINP nie je plynulosť animácie
Pamäť a stabilitaRozpočty, zmeny scényBez prenositeľného merania celej 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="/sk/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áťaž a kritériá: rovnaké dáta, počet objektov, animácie, interakcie, fyzické rozlíšenie, porovnateľný antialiasing, obnovovacia frekvencia, prehliadač, OS a režim napájania. Oddeľte inicializáciu a kompiláciu shaderov od stabilného behu. Opakujte vo vyváženom alebo náhodnom poradí, testujte mobily a teplotu. Nezovšeobecňujte výsledok jedného počítača. [5][25]

Kód vynechá 60 intervalov requestAnimationFrame, zhromaždí 300 a vypočíta medián, p95, p99 a prekročenia rozpočtu. Nearest rank: pozícia ceil(0,95 × N) v zoradenom poli. Intervaly callbackov nie sú čas GPU, prezentované snímky ani INP. Skrytý dokument znamená neplatný beh, platí timeout. Stabilita vyžaduje dlhší test. [25][26]

WebGL 2: čítajte EXT_disjoint_timer_query_webgl2 asynchrónne a zahoďte disjoint výsledky. WebGPU: aktivujte timestamp-query pri vytváraní zariadenia, ak je dostupné. performance.now okolo submit meria najmä odoslanie CPU. Interakcie a INP merajte samostatne. [27][28][29]

Prístupnosť, bezpečnosť a export

Súvisiace články POLPROG (anglicky): CSS Animations.

Bitmapa nesprístupňuje sémantiku objektov. Interaktívne grafy potrebujú HTML, klávesnicu, opis údajov a rovnocennú tabuľku. Hry a editory vyžadujú fokus, prístupné ovládanie, obmedzený pohyb a chybové hlásenia. Inline SVG ponúka viac možností, ale title a desc nezaručujú WCAG. [1][2][13]

Nevkladajte nedôveryhodné SVG ako surové HTML. Overte pôvod a CSP; na čítanie pixelov Canvas 2D z iného originu treba vhodné CORS hlavičky. Kontaminovaná bitmapa blokuje čítanie a export. toBlob môže vrátiť null alebo vyvolať výnimku bez origin-clean. WebGL a WebGPU majú vlastné obmedzenia textúr a prostriedkov. [14][15]

Výber technológie a hybridná architektúra

Výber technológie a hybridná architektúra
ScenárVýchodiskoPrečo
Ikony, diagramy, bežné grafySVGSémantika a škálovanie
Fotoeditor, kreslenie, jednoduchá 2D hraCanvas 2DPriamy prístup k bitmape
3D mapa, hra, hustá animovaná scénaWebGL 2 alebo WebGPUGPU po meraní
Paralelná simulácia, výpočet GPUWebGPUCompute shadery
Dashboard s mnohými bodmiCanvas 2D alebo GPU + HTML/SVGOddeliť grafiku a interakcie

Na ikony a diagramy začnite SVG, na kreslenie, pixely a jednoduché 2D hry Canvas 2D. Pre 3D a mnoho animovaných objektov vyhodnoťte WebGL 2 a WebGPU na cieľových zariadeniach. Pre compute shadery alebo moderné riadenie pipeline je WebGPU prirodzeným kandidátom. Naplánujte náhradu bez hardvérovej podpory.

Three.js, Babylon.js, PixiJS a D3 môžu znížiť náklady; overte renderery, efekty, veľkosť balíka a licencie. Zmena backendu niečo stojí. Ovládanie HTML, popisy SVG a Canvas/GPU pre hustú scénu sa dopĺňajú. Definujte spoločné údaje a súradnice; renderery vymeňte len pri rovnakých funkciách.

Three.js WebGPURenderer predvolene používa WebGPU a ponúka backend WebGL 2. PixiJS poskytuje viac 2D rendererov. Testujte konkrétne efekty a funkcie, nepredpokladajte zhodu backendov. [16][17]

Grafické knižnice a abstrakcie

Grafické knižnice a abstrakcie
KnižnicaPoužitieBackend a obmedzenia
Three.js3D scény, konfigurátoryWebGLRenderer alebo WebGPURenderer s WebGL 2 backendom; overte materiály a postprocessing
Babylon.js3D hry a aplikácieWebGL a WebGPU; rozdiely funkcií
PixiJS2D hry, animácie, sprityWebGL/WebGPU a Canvas podľa verzie; overte efekty a stav backendu
D3.jsDáta, škály, geometriaSVG alebo Canvas podľa implementácie
Konva.jsInteraktívne 2D editoryCanvas 2D s grafom a vrstvami; ďalšie bitmapy a hit testing

Knižnica môže ponúknuť graf scény, materiály, batching, udalosti a nástroje pre dáta. Porovnajte funkcie, backendy, veľkosť balíka, údržbu a licenciu. D3 je sada vizualizačných nástrojov, nie automatický GPU engine. [16][17][20][21][30]

Migrácia z WebGL 2 na WebGPU

Zachovajte WebGL 2, ak pokrýva požiadavky a cieľové zariadenia bez merateľného prínosu migrácie. WebGPU zvážte pre compute, záťaž CPU či nové funkcie knižnice; zrýchlenie nie je automatické. Pri novom 3D projekte najprv zvoľte knižnicu a overte scénu. [4][5][16][17]

Definujte požiadavky a rozpočty; oddeľte scénu a interakciu; stanovte kontrakty inicializácie, vykreslenia, resize a uvoľnenia; overte materiály, textúry, súradnice, farby a efekty; merajte zariadenia; nasadzujte postupne s fallbackom WebGL 2. Ponúknite CPU variant alebo oznámte chýbajúce compute funkcie. Neskrývajte významné rozdiely abstrakciou.

Overujte adapter, device, features a limits namiesto user agenta. Nemeňte typ kontextu inicializovaného canvas: vytvorte novú plochu, obnovte scénu a udalosti, uvoľnite predchádzajúci renderer. Testujte obe možnosti vrátane chýbajúcej GPU a straty zariadenia. [2][9][16][31]

Testovanie a nasadenie

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="/sk/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, []);
});

Rovnaký trojuholník ukazuje rozdiely API, nejde o benchmark. HTML a CSS sú oddelené, každý renderer má vlastnú plochu; pri chybe zostáva SVG a hlásenie. Unit testy pokrývajú rozpočty, neplatné údaje a extrémne pomery. V prehliadači overte výsledok, DPR, stratu kontextu/zariadenia, chýbajúce GPU a uvoľnenie prostriedkov. [5][7][9]

V CI používajte testy logiky a vizuálnej regresie s toleranciou rasterizácie. Pre výkon definujte scénu, akceptačné limity a časy snímok na cieľovom hardvéri; softvérový renderer nedokazuje hardvérový výkon. Overte klávesnicu, mobilné zariadenia, export a reinicializáciu, nielen úspech.

Začnite najjednoduchším modelom, ktorý spĺňa požiadavky. Pred zmenou renderera profilujte skutočnú scénu. WebGPU je zaujímavé pre náročné nové aplikácie, no SVG, Canvas 2D a WebGL zostávajú vhodné. Sémantické HTML so špecializovaným rendererom je často dobrý kompromis. Pred migráciou z WebGL 2 overte funkcie a merateľné prínosy. Oddeľte scénu, definujte životný cyklus zdrojov a otestujte všetky podporované renderery.

Canvas Canvas 2D SVG WebGL WebGPU WGSL Rendering Performance Accessibility TypeScript

Často kladené otázky

Nahrádza WebGPU WebGL?

Nie v každom projekte. WebGL 2 má širokú kompatibilitu; WebGPU vyberajte podľa funkcií a overenej podpory. [4][10][11]

Je Canvas vždy rýchlejší než SVG?

Nie. Náklady závisia od scény, aktualizácií, rozlíšenia a implementácie. [5][6]

Sú WebGL a WebGPU len pre 3D?

Nie. Obe API vykresľujú 2D; WebGPU ponúka compute shadery. [3][4]

Možno prepnúť WebGPU na WebGL na rovnakom canvas?

Nie po získaní kontextu. Nahraďte prvok alebo použite inú plochu. [2]

Ako zabrániť rozmazaniu Canvas na HiDPI?

Prispôsobte bitmapu CSS rozmerom a DPR v rámci rozpočtu; po zmene obnovte transformáciu. [6]

Zvyšuje OffscreenCanvas automaticky FPS?

Nie. Môže odľahčiť hlavné vlákno; závisí od záťaže a komunikácie. [12]

Ako sprístupniť graf Canvas?

Ponúknite rovnocenný text alebo tabuľku a prístupné ovládanie; testujte klávesnicu. [13]

Možno exportovať každý obraz Canvas?

Nie. Obrázky z iného originu bez CORS môžu blokovať čítanie a export. [14][15]

Potrebuje WebGPU pre compute canvas?

Nie. Compute pipeline spracúva a číta buffery bez GPUCanvasContext. [4][24]

Meria p95 intervalov čas GPU?

Nie nevyhnutne. requestAnimationFrame opisuje plánovanie callbackov; timestamp dotazy merajú vybrané GPU operácie. [25][27][28]

Zdroje a referencie

  1. W3C, Scalable Vector Graphics (SVG) 2↩1↩2↩3↩4↩5
  2. WHATWG, HTML Living Standard: canvas↩1↩2↩3↩4↩5↩6↩7↩8↩9
  3. Khronos, WebGL 2.0 specification↩1↩2↩3↩4↩5↩6
  4. W3C, WebGPU↩1↩2↩3↩4↩5↩6↩7↩8↩9↩10↩11↩12↩13
  5. MDN, WebGL best practices↩1↩2↩3↩4↩5↩6↩7↩8↩9↩10↩11↩12↩13↩14↩15↩16↩17
  6. MDN, Optimizing canvas↩1↩2↩3↩4↩5↩6↩7↩8
  7. MDN, webglcontextlost event↩1↩2↩3↩4
  8. W3C, WGSL Candidate Recommendation Draft, 28 November 2026↩1↩2↩3
  9. MDN, GPUDevice.lost↩1↩2↩3↩4
  10. web.dev, WebGPU is now supported in major browsers↩1↩2
  11. Can I use, WebGPU compatibility↩1↩2
  12. web.dev, OffscreenCanvas↩1↩2
  13. W3C, WCAG 2.2↩1↩2
  14. MDN, Use cross-origin images in a canvas↩1↩2
  15. MDN, HTMLCanvasElement.toBlob↩1↩2
  16. Three.js, WebGPURenderer↩1↩2↩3↩4
  17. PixiJS, Rendering↩1↩2↩3
  18. MDN, GPUAdapter.requestDevice↩
  19. W3C, WebGPU Candidate Recommendation Draft, 16 November 2026↩
  20. Babylon.js, WebGPU support↩1↩2
  21. Konva, performance tips↩1↩2↩3
  22. MDN, GPUComputePassEncoder.dispatchWorkgroups↩
  23. MDN, GPUSupportedLimits↩
  24. MDN, GPUBuffer.mapAsync↩1↩2
  25. MDN, requestAnimationFrame↩1↩2↩3
  26. MDN, Page Visibility API↩
  27. MDN, EXT_disjoint_timer_query↩1↩2
  28. MDN, GPUDevice.createQuerySet↩1↩2
  29. web.dev, Optimize Interaction to Next Paint↩
  30. D3, What is D3?↩
  31. MDN, HTMLCanvasElement.getContext↩

Bolo to užitočné?

Získavajte nové články e-mailom

Jeden krátky e-mail na každý nový článok Vzdelávania. Žiadny spam, odhlásenie jedným kliknutím.

Váš e-mail používame len na zasielanie nových článkov. Žiadne zdieľanie s tretími stranami.

Späť na Vzdelávanie