Kurzreferenz

HTML5 2D Canvas API Spickzettel

Kurzreferenz für HTML5 2D Canvas: Kontexterstellung, Grundformen, Pfade, Striche, Transformationen, Bildzeichnung und Statusverwaltung.

· Veröffentlicht

Eine kompakte Referenz für die HTML5 Canvas 2D Rendering Context API (CanvasRenderingContext2D).

Kontext abrufen

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

Grundformen & Füllungen

// Farben und Linienstile
ctx.fillStyle = '#ff0000';
ctx.strokeStyle = '#0000ff';
ctx.lineWidth = 4;
ctx.lineCap = 'round'; // 'butt' | 'round' | 'square'

// Direkte Rechtecke: x, y, Breite, Höhe
ctx.fillRect(10, 20, 200, 100);
ctx.strokeRect(10, 20, 200, 100);
ctx.clearRect(0, 0, canvas.width, canvas.height);

Pfade & benutzerdefinierte Formen

ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.lineTo(100, 150);
ctx.closePath();

ctx.fill();
ctx.stroke();

Bögen & Kreise

// arc(x, y, radius, startAngle, endAngle, counterClockwise)
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2, false);
ctx.stroke();

Zustandsstapel (Save & Restore)

ctx.save();    // Aktuellen Zustand auf den Stapel legen
// fillStyle, Transformationen, Clipping, Schatten anpassen...
ctx.restore(); // Vorherigen Zustand vom Stapel wiederherstellen

Der gespeicherte Zustand umfasst: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation und die aktuelle Transformationsmatrix.


Koordinatentransformationen

ctx.translate(dx, dy);
ctx.rotate(angleInRadians);
ctx.scale(scaleX, scaleY);

// Um einen benutzerdefinierten Ursprung (ox, oy) rotieren
ctx.translate(ox, oy);
ctx.rotate(angle);
ctx.translate(-ox, -oy);

Bilder zeichnen

const img = new Image();
img.onload = () => {
  // Vollständiges Bild an (x, y) zeichnen
  ctx.drawImage(img, 0, 0);

  // Skaliert zeichnen: (img, dx, dy, dWidth, dHeight)
  ctx.drawImage(img, 0, 0, 150, 100);

  // Zuschneiden und zeichnen: (img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
  ctx.drawImage(img, 50, 50, 100, 100, 0, 0, 100, 100);
};
img.src = 'picture.jpg';

Animationsschleifen-Muster

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // Frame-Elemente rendern...
  requestAnimationFrame(draw);
}
requestAnimationFrame(draw);

Verwandte Themen