Ir al contenido

Buscar

Artículos, herramientas, soluciones y guías de la base de conocimiento

Empieza a escribir para buscar artículos, herramientas y aplicaciones.

Canvas vs SVG vs WebGL vs WebGPU: ¿qué tecnología gráfica elegir?

La elección depende de la escena, las interacciones, la resolución y los dispositivos objetivo. Un gráfico empresarial, un editor de fotos y un motor de juegos tienen necesidades diferentes. Esta guía compara cuatro modelos de renderizado sin complejidad innecesaria.

Publicado Escrito por Tiempo de lectura 27 min de lectura
En esta página Índice: navegación rápida por las secciones

Modelos de renderizado: ¿qué comparamos?

Canvas vs SVG vs WebGL vs WebGPU
CriterioSVGCanvas 2DWebGL 2WebGPU
ModeloVectorialRasterizadoGráficos GPUGráficos y cálculo GPU
DOM por objetoSí, integradoNoNoNo
EscaladoVectorial salvo bitmapRedibujarRenderizar de nuevoRenderizar de nuevo
Compute shadersNoNoNo (técnicas indirectas)Sí
ComplejidadBaja–mediaBaja–mediaAltaAlta
CompatibilidadAmpliaAmpliaAmplia, depende de GPUDepende de plataforma y funciones

SVG conserva una descripción vectorial en un árbol de elementos. Canvas 2D dibuja en un mapa de bits sin conservar automáticamente los objetos. WebGL y WebGPU también utilizan canvas, pero ofrecen API de renderizado diferentes. canvas es un elemento HTML, no un único modelo de aceleración. [1][2][3][4]

SVG admite imágenes rasterizadas; Canvas 2D traza curvas vectoriales, pero produce un mapa de bits. El navegador puede acelerar ambos con GPU. Un contexto adquirido tiene tipo fijo; pasar de WebGPU a WebGL requiere otro canvas. [2][5]

Una escena raster requiere hit testing propio, mediante geometría o índice espacial. Leer identificadores desde un buffer GPU puede añadir latencia. SVG ofrece hit testing de elementos, condicionado por pointer-events, entre otros.

Retained mode e immediate mode: ¿quién conserva la escena?

Retained mode e immediate mode: ¿quién conserva la escena?
ModeloEjemploConsecuencias
Retained modeSVG, grafo de KonvaActualización de objetos; coste de almacenamiento y sincronización
Immediate modeCanvas 2D sin bibliotecaDibujo, hit testing y redibujado explícitos
Recursos y comandos GPUWebGL 2, WebGPULa aplicación gestiona geometría y recursos; sin semántica de objetos

En retained mode se conservan objetos y propiedades entre actualizaciones. En SVG integrado, el navegador gestiona el árbol; cambiar un atributo modifica la descripción del objeto. Canvas 2D modifica el mapa de bits directamente; mover un objeto requiere redibujar la zona afectada, no necesariamente cada fotograma. [1][2]

WebGL y WebGPU conservan recursos GPU, pero no un modelo de objetos de negocio, jerarquías o interacciones. Konva y Three.js pueden ofrecer un grafo de escena sobre un renderer raster. Separa documento, selección, historial e índice espacial del renderer. [5][20][21]

SVG: escala, semántica e interacción

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 es útil para iconos, diagramas, mapas vectoriales y gráficos interactivos. viewBox define coordenadas independientes del tamaño visible. SVG integrado permite acceder a DOM y CSS; dentro de img no expone un árbol interactivo al documento padre. [1]

Muchos nodos, cambios de atributos, filtros y geometrías complejas pueden aumentar el coste. Agrupar y simplificar trazados puede evitar migrar a GPU. El triángulo incluye descripción textual; un diagrama interactivo necesita además teclado y semántica.

Canvas 2D: resolución y presupuesto de memoria

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();
  };
}

Las dimensiones CSS difieren de las del bitmap. Con DPR 2, una superficie de 800 × 600 píxeles CSS utiliza 1600 × 1200 píxeles a resolución completa: cuatro veces más que DPR 1. RGBA8 ocupa unos 7,32 MiB sin buffers adicionales. Cambiar width o height reinicia el contexto; restaura la transformación y redibuja. [2][6]

El ejemplo limita píxeles y longitud del lado, dibuja con coordenadas normalizadas y elimina el observador y el listener. Los límites son un presupuesto de aplicación, no garantía del navegador. ResizeObserver y resize cubren cambios habituales; para seguir DPR con precisión observa también la densidad mediante matchMedia o devicePixelContentBoxSize con alternativa. [5][6]

WebGL 2: renderizado GPU y recursos

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 proporciona OpenGL ES 3.0, shaders GLSL ES, texturas, buffers, instancing y framebuffers. Es adecuado para juegos, mapas y escenas 3D. En vez de modificar miles de nodos DOM, prepara datos y comandos. Draw calls, shaders, texturas y píxeles determinan el coste. [3][5]

El ejemplo genera tres vértices en el shader, verifica compilación y enlace, ajusta el viewport y reconstruye el programa tras webglcontextrestored. Los recursos anteriores dejan de ser válidos. Evita preserveDrawingBuffer por defecto debido a su coste. El bitmap estático es fijo; una escena dinámica requiere redibujado y sincronización de tamaño. [5][7]

WebGPU: renderizado moderno y cálculo

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 expone explícitamente device, queue, recursos, bind groups y pipelines de renderizado y cálculo. Los shaders suelen escribirse en WGSL. Los compute shaders permiten cálculos paralelos; tareas pequeñas, transferencias y lecturas de retorno pueden anular la ventaja. [4][8]

El ejemplo inicializa adaptador y dispositivo en contexto seguro, selecciona formato, crea pipeline de forma asíncrona, codifica el render pass y envía comandos. Gestiona ausencia de adaptador, errores de validación y pérdida del dispositivo, y libera recursos. Una pérdida requiere reconstrucción o cambio de renderer; no hay reinicialización automática. [4][9]

A 30/11/2026 WebGPU está disponible en las principales familias de navegadores, pero la cobertura de plataformas y funciones varía. Comprueba requestAdapter(), requestDevice(), features y limits, no solo navigator.gpu. Implementación y estado formal W3C son cuestiones distintas. [4][10][11]

La publicación W3C del 16/11/2026 clasifica WebGPU como Candidate Recommendation Draft; WGSL también sigue el proceso de estandarización. Comprueba adapter.features y adapter.limits antes de requestDevice() y solicita solo lo necesario. [18][19]

Pipeline de renderizado: WebGL 2 frente a WebGPU

Pipeline de renderizado: WebGL 2 frente a WebGPU
CriterioWebGL 2WebGPU
ShadersGLSL ES 3.00WGSL
EstadoContexto mutablePipeline, bind groups, estado parcialmente dinámico
ComandosLlamadas al contextoCommand encoder, pass, command buffer, queue
CálculoTransform feedback, renderizado a texturaCompute pipelines y storage buffers
RecursosBuffers y texturas, enlaces dependientes del estadoUsage flags y layouts explícitos
SincronizaciónFences; lectura potencialmente bloqueanteCola, mapAsync, reglas de uso de recursos
ErroresCompilación, enlace, contextoError scopes, errores asíncronos, device.lost
Funciones opcionalesExtensiones y límites del contextoFeatures y limits del adaptador y dispositivo

El vertex shader calcula posiciones en el espacio de recorte. La rasterización genera fragmentos e interpola atributos; el fragment shader calcula salidas y las pruebas de profundidad y blending afectan al destino. Un fragmento no equivale siempre a un píxel final (MSAA, superposición). Los compute shaders trabajan en grupos sin rasterización. [3][4][8]

WebGL 2 usa estado mutable del contexto. WebGPU agrupa configuración en pipelines y codifica pases y command buffers. Enviar comandos a la cola no significa que la GPU haya terminado. WebGPU gestiona la sincronización según sus reglas, sin barreras manuales como Vulkan. [3][4][5]

Compute shader sin renderizar una escena

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();
  }
}

El ejemplo duplica Uint32Array módulo 2^32. Cada invocación procesa un elemento; la comprobación WGSL protege el último grupo parcial. Dispatch ceil(N/64), dos grupos de 64 para 65 valores. Un millón de elementos es el presupuesto de la demo; se comprueban límites de buffers, bindings y grupos. [4][8][22][23]

Sube datos a STORAGE con COPY_DST y COPY_SRC, ejecuta dispatch y copia a MAP_READ | COPY_DST. Tras mapAsync copia los valores a un array independiente, llama a unmap y libera ambos buffers. El dispositivo pertenece a la operación; uno compartido necesita su propio ciclo de vida. Error scopes cubren validación, memoria y errores internos. [4][24]

No demuestra una mejora de velocidad para una multiplicación trivial. Compara con CPU incluyendo 0, 65 elementos y desbordamiento u32. En producción reutiliza dispositivos, pipelines y buffers; evita leer tras cada operación. Simulaciones de partículas y filtros son candidatos si compensan las transferencias.

Ventajas, limitaciones y garantías

Ventajas, limitaciones y garantías
CriterioVentajasDesventajasNo garantiza
SVGEscalado, DOM y CSSCoste de nodos y filtrosAccesibilidad completa
Canvas 2DDibujo sencillo y píxelesInteracción propia, memoria bitmapRendimiento constante
WebGL 2API GPU madura, ecosistema 3DEstado complejo, sin API computeFluidez y todos los dispositivos
WebGPUPipelines explícitos, compute shadersInicialización, compatibilidad, recursosVentaja en toda escena

La comparación describe propiedades típicas, no benchmarks. Una escena SVG sencilla y poco actualizada puede superar un renderer GPU mal diseñado. No existe un umbral universal de objetos. Decide según el perfil de carga y los requisitos del producto. [5][6]

Gestión de recursos y coste de escena

Instancing dibuja geometría compartida con parámetros por instancia. Batching agrupa comandos compatibles y reduce cambios de estado y draw calls. Respeta blending, orden y culling. Simplifica nodos y geometría SVG; en Canvas 2D considera capas y renderizado bajo demanda. [5][6][21]

Presupuesta buffers, texturas, mipmaps, depth/stencil, MSAA y destinos intermedios. Una textura RGBA8 de 4096 × 4096 ocupa 64 MiB en el nivel base y unos 85,33 MiB con toda la cadena mip, sin sobrecarga ni compresión. No presupongas acceso a toda la VRAM. [5]

Separa recursos compartidos y de escena. Elimina programas, buffers y texturas WebGL; destruye buffers y texturas WebGPU innecesarios y el dispositivo al acabar su ciclo de vida. Cancela animaciones y observadores. Reconstruye desde la escena tras perder contexto o dispositivo; no guardes la única copia de datos esenciales en GPU. [5][7][9]

Medición y optimización del rendimiento

Artículos POLPROG relacionados: Critical Rendering Path, Long Tasks, Main Thread e INP.

A 60 Hz el presupuesto nominal por fotograma es de 16,67 ms; a 120 Hz, 8,33 ms, incluido el navegador. Además de FPS mide percentiles de tiempo de fotograma, latencia, inicialización, memoria y estabilidad. Compara escenas, tamaños, DPR, calidad y dispositivos idénticos; separa el calentamiento de shaders.

Reduce draw calls, cambios de estado, actualizaciones DOM innecesarias y lecturas GPU síncronas. Canvas 2D permite renderizar bajo demanda, guardar capas estáticas y usar OffscreenCanvas. Un worker puede aliviar el hilo principal, no necesariamente el GPU; considera mensajes, transferencias y ciclo de vida. Mide INP y Long Tasks. [5][6][12]

Metodología de benchmark

Metodología de benchmark
MétricaMediciónRiesgo
InicioTiempo hasta escena utilizableSepara pruebas frías y calientes
IntervalosMediana, p95, p99, exceso de presupuestoFPS puede ocultar tirones
CPU y GPUPerfil del hilo principal y consultas GPU opcionalesSubmit no indica finalización
InteracciónLatencia de controles e INPINP no mide fluidez de animación
Memoria y estabilidadPresupuestos, cambios de escenaSin medición portable de VRAM total

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="/es/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 carga y aceptación: mismos datos, objetos, animación, interacción, resolución física, antialiasing comparable, frecuencia, navegador, sistema y modo de energía. Separa inicio y compilación de shaders del régimen estable. Repite en orden equilibrado o aleatorio, prueba móviles y temperatura; no generalices desde un equipo. [5][25]

El código descarta 60 intervalos de requestAnimationFrame, recoge 300 y calcula mediana, p95, p99 y exceso de presupuesto. Nearest rank: posición ceil(0,95 × N) en datos ordenados. Son intervalos de callbacks, no tiempo GPU, fotogramas presentados ni INP. Descarta ensayos si el documento se oculta y aplica timeout. Usa pruebas más largas para estabilidad. [25][26]

WebGL 2: consulta EXT_disjoint_timer_query_webgl2 de forma asíncrona y descarta resultados disjoint. WebGPU: activa timestamp-query al crear el dispositivo si está disponible. performance.now alrededor de submit mide principalmente envío CPU. Mide interacción e INP por separado. [27][28][29]

Accesibilidad, seguridad y exportación

Artículos POLPROG relacionados: Animaciones CSS.

Un bitmap no expone semántica de objetos. Para gráficos interactivos proporciona HTML, teclado, descripciones y tabla equivalente. Juegos y editores requieren foco, controles accesibles, movimiento reducido y mensajes de error. SVG integrado ofrece más opciones, pero title y desc no garantizan WCAG. [1][2][13]

No insertes SVG no confiable como HTML sin tratar. Comprueba origen y CSP; para leer píxeles Canvas 2D de imágenes de otro origen hacen falta cabeceras CORS apropiadas. Un bitmap contaminado bloquea lectura y exportación. toBlob puede devolver null o lanzar excepción si no es origin-clean. WebGL y WebGPU tienen restricciones propias de texturas y recursos. [14][15]

Selección y arquitectura híbrida

Selección y arquitectura híbrida
EscenarioPunto de partidaPor qué
Iconos, diagramas, gráficos clásicosSVGSemántica y escalado
Editor de fotos, dibujo, juego 2D simpleCanvas 2DAcceso directo a bitmap
Mapa 3D, juego, escena animada densaWebGL 2 o WebGPUGPU tras medir
Simulación paralela, cálculo GPUWebGPUCompute shaders
Panel con muchos puntosCanvas 2D o GPU + HTML/SVGSeparar gráficos e interacción

Empieza con SVG para iconos y diagramas, Canvas 2D para dibujo, píxeles y juegos 2D simples. Para 3D y escenas animadas densas evalúa WebGL 2 y WebGPU en dispositivos objetivo. Si necesitas compute shaders o control moderno de pipelines, WebGPU es candidato natural. Prevé alternativa cuando falte soporte.

Three.js, Babylon.js, PixiJS y D3 pueden reducir trabajo; revisa renderers, efectos, tamaño y licencias. Cambiar backend tiene coste. Controles HTML, etiquetas SVG y Canvas/GPU para escenas densas se complementan. Define modelo común de datos y coordenadas; intercambia renderers solo cuando sus prestaciones sean equivalentes.

Three.js WebGPURenderer utiliza WebGPU por defecto y ofrece backend WebGL 2. PixiJS tiene varios renderers 2D. Prueba los efectos y funciones concretos sin asumir paridad entre backends. [16][17]

Bibliotecas gráficas y abstracción

Bibliotecas gráficas y abstracción
BibliotecaUsoBackend y límites
Three.jsEscenas 3D, configuradoresWebGLRenderer o WebGPURenderer con backend WebGL 2; comprueba materiales y posprocesado
Babylon.jsJuegos y aplicaciones 3DWebGL y WebGPU; diferencias de funciones
PixiJSJuegos 2D, animación, spritesWebGL/WebGPU y Canvas según versión; comprueba efectos y estado del backend
D3.jsDatos, escalas, geometríaSVG o Canvas según implementación
Konva.jsEditores 2D interactivosCanvas 2D con grafo y capas; bitmaps adicionales y hit testing

Una biblioteca puede aportar grafo de escena, materiales, batching, eventos o utilidades de datos. Compara funciones necesarias, backends, tamaño del paquete, mantenimiento y licencia. D3 es una caja de herramientas de visualización, no un motor GPU automático. [16][17][20][21][30]

Migración de WebGL 2 a WebGPU sin reescritura forzada

Conserva WebGL 2 si cubre requisitos y dispositivos y no hay beneficio medido. Estudia WebGPU para compute, sobrecarga CPU o nuevas funciones de biblioteca, sin asumir mejora automática. Para un nuevo producto 3D, elige biblioteca y verifica la escena primero. [4][5][16][17]

Define requisitos y presupuestos; separa escena e interacción; fija contratos de inicialización, dibujo, redimensionado y liberación; prueba materiales, texturas, coordenadas, colores y efectos; mide dispositivos; despliega gradualmente con alternativa WebGL 2. Ofrece variante CPU o comunica funciones compute no disponibles. No ocultes diferencias importantes con una abstracción.

Comprueba adapter, device, features y limits en vez del user agent. No cambies el tipo de contexto de un canvas inicializado: crea otra superficie, restaura escena y eventos, libera el renderer anterior. Prueba ambas rutas, incluida ausencia de GPU y pérdida de dispositivo. [2][9][16][31]

Pruebas y despliegue

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

El mismo triángulo demuestra diferencias de API, no es benchmark. HTML y CSS están separados; cada renderer tiene su superficie. Si falla, SVG y mensaje quedan disponibles. Pruebas unitarias cubren presupuesto, datos inválidos y proporciones extremas. En navegador comprueba resultado, DPR, pérdida de contexto/dispositivo, GPU ausente y liberación. [5][7][9]

En CI usa pruebas de lógica y regresión visual con tolerancia de rasterización. Para rendimiento define escena, umbrales y tiempos en hardware objetivo; un renderer software no demuestra rendimiento físico. Comprueba teclado, móviles, exportación y reinicialización, no solo el caso correcto.

Empieza por el modelo más sencillo que cumpla los requisitos. Perfila la escena real antes de cambiar de motor. WebGPU interesa para aplicaciones nuevas exigentes, pero SVG, Canvas 2D y WebGL siguen siendo opciones válidas. Combinar HTML semántico con un motor especializado suele ser un buen compromiso. Antes de migrar desde WebGL 2, comprueba funciones y beneficios medidos. Separa la escena, define el ciclo de vida de recursos y prueba todos los renderers compatibles.

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

Preguntas frecuentes

¿WebGPU sustituye a WebGL?

No en todos los proyectos. WebGL 2 tiene amplia compatibilidad; elige WebGPU según las funciones y el soporte comprobado. [4][10][11]

¿Canvas siempre es más rápido que SVG?

No. El coste depende de escena, actualizaciones, resolución e implementación. [5][6]

¿WebGL y WebGPU son solo para 3D?

No. Ambos renderizan 2D y WebGPU aporta compute shaders. [3][4]

¿Puedo cambiar WebGPU por WebGL en el mismo canvas?

No tras adquirir el contexto. Sustituye el elemento o usa otra superficie. [2]

¿Cómo evito Canvas borroso en HiDPI?

Adapta el bitmap a tamaño CSS y DPR dentro del presupuesto; restaura la transformación después del cambio. [6]

¿OffscreenCanvas aumenta automáticamente FPS?

No. Puede aliviar el hilo principal; depende de la carga y comunicación. [12]

¿Cómo hago accesible un gráfico Canvas?

Proporciona texto o tabla equivalente y controles accesibles; prueba el teclado. [13]

¿Puedo exportar cualquier imagen Canvas?

No. Imágenes de otro origen sin permiso CORS pueden bloquear lectura y exportación. [14][15]

¿El cálculo WebGPU necesita canvas?

No. Un compute pipeline procesa y lee buffers sin GPUCanvasContext. [4][24]

¿El p95 de intervalos mide tiempo GPU?

No necesariamente. requestAnimationFrame refleja la programación de callbacks; las consultas timestamp miden operaciones GPU concretas. [25][27][28]

Fuentes y referencias

  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↩

¿Te ha resultado útil?

Recibe nuevos artículos por email

Un correo breve por cada nuevo artículo de la base de conocimiento. Sin spam, te das de baja con un clic.

Solo usamos tu email para enviar nuevos artículos. Sin compartir con terceros.

Volver a la base de conocimiento