Start · Sprachen · JavaScript · Referenz · GPUCanvasContext.configure()

GPUCanvasContext.configure()

Methode

Verbindet einen <code>GPUCanvasContext</code> mit einem <code>GPUDevice</code> und legt Texturformat, Verwendung, Alpha-Modus und Farbraum der Canvas-Texturen fest.

seit JavaScript WebGPU – Chrome/Edge 113+, Safari 26+, Firefox 141 Kategorie: webapi

Signatur

GPUCanvasContext.prototype.configure(configuration)

Beschreibung

configure() ist der Pflichtschritt zwischen canvas.getContext("webgpu") und dem ersten Rendern. Die Methode verknüpft den Canvas-Kontext mit einem konkreten GPUDevice. Erst danach liefert getCurrentTexture() eine GPUTexture, in die ein Render-Pass zeichnen kann.

Über das Konfigurationsobjekt legst du fest, in welchem Texturformat die Canvas-Texturen angelegt werden. Empfohlen ist fast immer navigator.gpu.getPreferredCanvasFormat(), meist "bgra8unorm" oder "rgba8unorm". Außerdem bestimmst du, wie Alpha mit der Seite verrechnet wird (alphaMode), welchen Farbraum die Ausgabe nutzt (colorSpace) und wofür die Textur gebraucht wird (usage). Über toneMapping steuerst du bei Bedarf die HDR-Ausgabe.

Du kannst configure() jederzeit erneut aufrufen, zum Beispiel wenn du auf ein anderes Device wechselst oder nach einem Geräteverlust (device.lost). Jeder neue Aufruf verwirft die aktuelle Textur. Mit unconfigure() hebst du die Konfiguration wieder auf. Ändert sich die Größe des Canvas (canvas.width/height), musst du nicht neu konfigurieren: Die nächste Textur aus getCurrentTexture() hat automatisch die neue Größe.

Parameter

Name Typ Default Beschreibung
$configuration Pflicht GPUCanvasConfiguration Konfigurationsobjekt mit den unten aufgeführten Eigenschaften.
$configuration.device Pflicht GPUDevice Das GPUDevice, das die Canvas-Texturen erzeugt und in sie rendert.
$configuration.format Pflicht GPUTextureFormat Texturformat der Canvas-Texturen. Erlaubt sind nur "bgra8unorm", "rgba8unorm" und "rgba16float".
$configuration.usage number (GPUTextureUsageFlags) GPUTextureUsage.RENDER_ATTACHMENT Bitmaske, wofür die Textur verwendet wird, z. B. zusätzlich GPUTextureUsage.COPY_SRC für Screenshots oder STORAGE_BINDING für Compute-Shader.
$configuration.viewFormats GPUTextureFormat[] [] Weitere Formate für texture.createView(), z. B. die sRGB-Variante "bgra8unorm-srgb".
$configuration.colorSpace "srgb" | "display-p3" "srgb" Farbraum, in dem die Seite die Textur-Werte interpretiert.
$configuration.alphaMode "opaque" | "premultiplied" "opaque" "opaque" ignoriert Alpha. Mit "premultiplied" wird das Canvas mit vormultipliziertem Alpha über die Seite gelegt, sodass Transparenz möglich ist.
$configuration.toneMapping { mode: "standard" | "extended" } { mode: "standard" } "extended" lässt bei HDR-fähigen Displays Werte über 1.0 zu. Sinnvoll nur zusammen mit "rgba16float".

Rückgabewert

Typ
undefined
Beschreibung
Kein Rückgabewert. Ab dem Aufruf liefert context.getCurrentTexture() passend konfigurierte Texturen.

Beispiele

Grundkonfiguration und Canvas einfärben

const init = async () => {
  if (!navigator.gpu) throw new Error('WebGPU wird nicht unterstützt');

  const adapter = await navigator.gpu.requestAdapter();
  const device = await adapter.requestDevice();

  const canvas = document.querySelector('canvas');
  const context = canvas.getContext('webgpu');
  const format = navigator.gpu.getPreferredCanvasFormat();

  context.configure({ device, format, alphaMode: 'opaque' });

  // Einmal mit Blau löschen
  const encoder = device.createCommandEncoder();
  const pass = encoder.beginRenderPass({
    colorAttachments: [{
      view: context.getCurrentTexture().createView(),
      clearValue: { r: 0.1, g: 0.3, b: 0.8, a: 1 },
      loadOp: 'clear',
      storeOp: 'store'
    }]
  });
  pass.end();
  device.queue.submit([encoder.finish()]);
  console.log('Konfiguriert mit Format:', format);
};

init();
Konfiguriert mit Format: bgra8unorm

Transparentes Canvas mit sRGB-View

const setupTransparent = (device, canvas) => {
  const context = canvas.getContext('webgpu');
  const format = navigator.gpu.getPreferredCanvasFormat();

  context.configure({
    device,
    format,
    alphaMode: 'premultiplied', // Seite scheint durch
    viewFormats: [`${format}-srgb`],
    usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  });

  // View mit automatischer sRGB-Kodierung erstellen
  const view = context.getCurrentTexture().createView({ format: `${format}-srgb` });
  return { context, view };
};

Neu konfigurieren nach Geräteverlust

const startRenderer = async (canvas) => {
  const adapter = await navigator.gpu.requestAdapter();
  const device = await adapter.requestDevice();
  const context = canvas.getContext('webgpu');

  context.configure({
    device,
    format: navigator.gpu.getPreferredCanvasFormat()
  });

  device.lost.then((info) => {
    console.warn('Gerät verloren:', info.message);
    if (info.reason !== 'destroyed') {
      context.unconfigure();
      startRenderer(canvas); // neues Device, neue Konfiguration
    }
  });

  return { device, context };
};

// Wichtig · Fallstricke

  • Ungültiges Format: Andere Formate als bgra8unorm, rgba8unorm und rgba16float lösen einen TypeError aus. Auch *-srgb-Formate sind hier nicht erlaubt; gib sie stattdessen über viewFormats an.
  • Bevorzugtes Format: Ein anderes Format als getPreferredCanvasFormat() funktioniert zwar, kann auf manchen Plattformen aber eine zusätzliche Kopie kosten, etwa rgba8unorm unter macOS oder Android.
  • Pipeline-Format: Das Format im fragment.targets deiner Render-Pipeline muss zum konfigurierten Format passen, sonst meldet WebGPU einen Validierungsfehler.
  • Eine Textur pro Frame: Rufe getCurrentTexture() in jedem Frame neu auf. Eine Textur aus einem früheren Frame ist nach der Darstellung ungültig.
  • Größe ändern: Wenn sich die Canvas-Größe ändert, musst du nicht neu konfigurieren. Setze nur canvas.width/height, idealerweise mit devicePixelRatio multipliziert.
  • Kompatibilität: WebGPU gibt es nur in sicheren Kontexten (HTTPS). Unterstützt wird es in Chromium ab 113 und in neueren Safari- und Firefox-Versionen, auf manchen Plattformen noch eingeschränkt. Prüfe deshalb immer navigator.gpu und sieh einen WebGL-Fallback vor.
  • Auch in Workern: configure() funktioniert auch mit einem OffscreenCanvas in einem Worker.