Start · Sprachen · JavaScript · Referenz · CanvasRenderingContext2D

CanvasRenderingContext2D

Schnittstelle

Stellt den 2D-Zeichenkontext eines <code>&lt;canvas&gt;</code>-Elements bereit – mit Methoden für Formen, Pfade, Text, Bilder, Transformationen und Pixelzugriff.

seit JavaScript Baseline: alle Browser Kategorie: webapi

Signatur

interface CanvasRenderingContext2D

Beschreibung

Das Interface CanvasRenderingContext2D gehört zur Canvas-API und ist das zentrale Werkzeug, um auf die Bitmap-Zeichenfläche eines <canvas>-Elements zu zeichnen. Eine Instanz bekommst du nicht über einen Konstruktor, sondern über canvas.getContext("2d"). Jedes Canvas-Element hat genau einen 2D-Kontext. Rufst du getContext("2d") mehrmals auf, bekommst du immer dasselbe Objekt zurück.

Der Kontext arbeitet im Immediate Mode: Gezeichnete Formen werden sofort in Pixel umgewandelt und nicht als Objekte gespeichert. Für Animationen oder interaktive Grafiken musst du die Szene deshalb bei jeder Änderung selbst neu zeichnen, meist mit clearRect() und requestAnimationFrame(). Zum Kontext gehören:

  • Rechtecke: fillRect(), strokeRect(), clearRect()
  • Pfade: beginPath(), moveTo(), lineTo(), arc(), bezierCurveTo(), roundRect(), fill(), stroke(), clip()
  • Stile: fillStyle, strokeStyle, lineWidth, globalAlpha, shadowBlur, filter, Verläufe (createLinearGradient()) und Muster (createPattern())
  • Text: fillText(), strokeText(), measureText(), font, textAlign, textBaseline
  • Bilder und Pixel: drawImage(), getImageData(), putImageData(), createImageData()
  • Transformationen: translate(), rotate(), scale(), setTransform(), resetTransform()
  • Zustand: save() und restore() legen alle Stil-, Transformations- und Clipping-Einstellungen auf einem Stapel ab und stellen sie wieder her.

Du nutzt den 2D-Kontext für Diagramme, Spiele, Bildbearbeitung, Signaturfelder, Generatoren für Vorschaubilder oder Visualisierungen mit vielen Elementen. Hier ist ein Canvas oft schneller als SVG oder DOM. Für 3D-Grafik oder sehr rechenintensive Darstellungen sind WebGL oder WebGPU besser geeignet.

Parameter

Name Typ Default Beschreibung
$contextType Pflicht "2d" Wird an HTMLCanvasElement.getContext() übergeben, damit du einen CanvasRenderingContext2D bekommst.
$contextAttributes { alpha?: boolean, desynchronized?: boolean, colorSpace?: "srgb" | "display-p3", willReadFrequently?: boolean } { alpha: true, colorSpace: "srgb", willReadFrequently: false } Optionale Einstellungen für den Kontext. alpha: false macht die Zeichenfläche undurchsichtig, was schneller sein kann. willReadFrequently: true beschleunigt häufige Aufrufe von getImageData(). colorSpace legt den Farbraum fest.

Rückgabewert

Typ
CanvasRenderingContext2D | null
Beschreibung
getContext("2d") gibt den 2D-Kontext zurück. Du bekommst null, wenn für das Canvas schon ein anderer Kontexttyp angelegt wurde, zum Beispiel "webgl".

Beispiele

Kontext holen und einfache Formen zeichnen

const canvas = document.querySelector('#bühne');
const ctx = canvas.getContext('2d');

// Gefülltes Rechteck
ctx.fillStyle = '#3b82f6';
ctx.fillRect(20, 20, 120, 80);

// Kreis mit Umrandung
ctx.beginPath();
ctx.arc(220, 60, 40, 0, Math.PI * 2);
ctx.strokeStyle = 'crimson';
ctx.lineWidth = 4;
ctx.stroke();

// Text
ctx.font = 'bold 20px system-ui';
ctx.fillStyle = '#111';
ctx.fillText('Hallo Canvas', 20, 140);
console.log(ctx instanceof CanvasRenderingContext2D);
true

Scharfe Darstellung auf HiDPI-Bildschirmen

const setupCanvas = (canvas) => {
  const dpr = window.devicePixelRatio || 1;
  const { width, height } = canvas.getBoundingClientRect();
  canvas.width = Math.round(width * dpr);
  canvas.height = Math.round(height * dpr);
  const ctx = canvas.getContext('2d');
  ctx.scale(dpr, dpr); // ab jetzt in CSS-Pixeln zeichnen
  return ctx;
};

const ctx = setupCanvas(document.querySelector('canvas'));
ctx.fillRect(10, 10, 100, 50);
console.log(ctx.getTransform().a);
2 (auf einem Retina-Display)

Animation mit save/restore und Transformation

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
let winkel = 0;

const zeichne = () => {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.save();
  ctx.translate(canvas.width / 2, canvas.height / 2);
  ctx.rotate(winkel);
  ctx.fillStyle = 'orange';
  ctx.fillRect(-40, -40, 80, 80); // um die eigene Mitte drehen
  ctx.restore();
  winkel += 0.02;
  requestAnimationFrame(zeichne);
};

requestAnimationFrame(zeichne);

Bild laden und in Graustufen umwandeln

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d', { willReadFrequently: true });

const img = new Image();
img.src = '/bilder/foto.jpg'; // gleiche Herkunft, sonst wird das Canvas "tainted"
await img.decode();

canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
ctx.drawImage(img, 0, 0);

const bild = ctx.getImageData(0, 0, canvas.width, canvas.height);
const d = bild.data;
for (let i = 0; i < d.length; i += 4) {
  const grau = 0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2];
  d[i] = d[i + 1] = d[i + 2] = grau;
}
ctx.putImageData(bild, 0, 0);
console.log(`${d.length / 4} Pixel verarbeitet`);
z. B. "307200 Pixel verarbeitet"