Signatur
Beschreibung
getContext() ist der Einstieg in jede Zeichenoperation auf einem <canvas>-Element. Das Canvas selbst ist nur eine Pixelfläche; erst der zurückgegebene Rendering-Kontext stellt die eigentlichen Zeichenmethoden bereit, etwa fillRect() beim 2D-Kontext oder Shader- und Buffer-Funktionen bei WebGL.
Welcher Kontext entsteht, bestimmt der Parameter contextType:
"2d"– liefert einCanvasRenderingContext2Dfür 2D-Grafik (Formen, Text, Bilder)."webgl"– liefert einWebGLRenderingContext(WebGL 1, basiert auf OpenGL ES 2.0)."webgl2"– liefert einWebGL2RenderingContext(basiert auf OpenGL ES 3.0)."webgpu"– liefert einGPUCanvasContextfür WebGPU."bitmaprenderer"– liefert einImageBitmapRenderingContext, das nur einImageBitmapanzeigt (transferFromImageBitmap()).
Ein Canvas kann immer nur einen Kontexttyp haben. Der erste erfolgreiche Aufruf legt ihn fest. Weitere Aufrufe mit demselben Typ geben dasselbe Objekt zurück, ein Aufruf mit einem anderen Typ liefert null. Deshalb ruft man getContext() meist einmal auf und merkt sich das Ergebnis in einer Variablen.
Über das optionale Objekt contextAttributes legt man Eigenschaften des Kontexts fest, etwa Transparenz, Antialiasing oder Hinweise zur Leistung. Diese Attribute gelten nur beim ersten Aufruf; spätere Aufrufe ignorieren sie.
Parameter
| Name | Typ | Default | Beschreibung |
|---|---|---|---|
| $contextType Pflicht | "2d" | "webgl" | "webgl2" | "webgpu" | "bitmaprenderer" | Bezeichner des gewünschten Kontexts. Groß- und Kleinschreibung zählt. Bei unbekannten Werten ist das Ergebnis null. Veraltet: "experimental-webgl". |
|
| $contextAttributes | object | {} | Optionen für den Kontext. 2d: alpha (boolean, Standard true), willReadFrequently (boolean, sinnvoll bei häufigem getImageData()), desynchronized (boolean, weniger Latenz), colorSpace ("srgb" | "display-p3"). WebGL: alpha, antialias, depth, stencil, premultipliedAlpha, preserveDrawingBuffer, powerPreference ("default" | "high-performance" | "low-power"), failIfMajorPerformanceCaveat, desynchronized. bitmaprenderer: alpha. |
Rückgabewert
null, wenn der Typ nicht unterstützt wird, WebGL nicht verfügbar ist (z. B. Blocklist des GPU-Treibers) oder das Canvas schon einen anderen Kontexttyp hat.Beispiele
2D-Kontext holen und ein Rechteck mit Text zeichnen
// HTML: <canvas id="chart" width="300" height="150"></canvas>
const canvas = document.getElementById('chart');
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error('2D-Canvas wird nicht unterstützt');
}
ctx.fillStyle = '#2563eb';
ctx.fillRect(20, 20, 120, 80);
ctx.fillStyle = '#111';
ctx.font = '16px sans-serif';
ctx.fillText('Umsatz Q1', 20, 130);
console.log(ctx instanceof CanvasRenderingContext2D);
WebGL2 mit Rückfall auf WebGL 1 und 2D
const createContext = (canvas) => {
const attrs = { antialias: true, powerPreference: 'high-performance' };
const gl2 = canvas.getContext('webgl2', attrs);
if (gl2) return { type: 'webgl2', ctx: gl2 };
const gl1 = canvas.getContext('webgl', attrs);
if (gl1) return { type: 'webgl', ctx: gl1 };
// Hinweis: nur möglich, weil die Versuche oben null lieferten
return { type: '2d', ctx: canvas.getContext('2d') };
};
const canvas = document.createElement('canvas');
const { type, ctx } = createContext(canvas);
console.log('Aktiver Kontext:', type);
if (type !== '2d') {
ctx.clearColor(0.1, 0.1, 0.1, 1);
ctx.clear(ctx.COLOR_BUFFER_BIT);
}
Nur ein Kontexttyp pro Canvas
const canvas = document.createElement('canvas');
const a = canvas.getContext('2d');
const b = canvas.getContext('2d');
const c = canvas.getContext('webgl');
console.log(a === b); // gleiche Instanz
console.log(c); // anderer Typ -> null
Häufiges Pixel-Auslesen mit willReadFrequently
const canvas = document.createElement('canvas');
canvas.width = canvas.height = 100;
// Hält die Daten im Arbeitsspeicher der CPU, damit getImageData schneller läuft
const ctx = canvas.getContext('2d', { willReadFrequently: true, alpha: false });
ctx.fillStyle = 'rgb(255, 0, 0)';
ctx.fillRect(0, 0, 100, 100);
const [r, g, b, a] = ctx.getImageData(50, 50, 1, 1).data;
console.log({ r, g, b, a });
console.log(ctx.getContextAttributes().willReadFrequently);