HTML:HTML5 Canvas API: 2D-Zeichnungen und Animationen
HTML•Canvas 2D

HTML5 Canvas API: 2D-Zeichnungen und Animationen

Lerne die Canvas 2D-Kontext-API: Rechtecke, Pfade, Kreise und Grafiken in Echtzeit rendern.

Syntax

const ctx = canvas.getContext("2d"); ctx.fillRect(x, y, w, h);

Parameter & Werte

Wichtige Bestandteile und zulässige Werte für diese Struktur:

ParameterTypBeschreibung
getContext("2d")MethodLiefert das CanvasRenderingContext2D-Objekt zum 2D-Zeichnen.

Ausführbares Code-Beispiel

In Compilra ausführbar

Führe dieses vollständige Beispiel direkt aus, ohne HTML lokal zu installieren:

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; padding: 20px; text-align: center; }
    canvas { border: 2px solid #0f172a; border-radius: 8px; background: #0f172a; }
  </style>
</head>
<body>
  <h2>HTML5 2D Canvas Graphics</h2>
  <canvas id="myCanvas" width="300" height="150"></canvas>

  <script>
    const canvas = document.querySelector("#myCanvas");
    const ctx = canvas.getContext("2d");

    // Draw background gradient rectangle
    ctx.fillStyle = "#3b82f6";
    ctx.fillRect(30, 30, 90, 90);

    // Draw circle
    ctx.beginPath();
    ctx.arc(200, 75, 45, 0, Math.PI * 2);
    ctx.fillStyle = "#10b981"; // Emerald green
    ctx.fill();

    // Render text
    ctx.fillStyle = "#ffffff";
    ctx.font = "14px sans-serif";
    ctx.fillText("Compilra 2D", 40, 80);
  </script>
</body>
</html>
Erwartete Ausgabe:
[Rendered HTML5 2D Canvas: Dark Viewport with Blue Rectangle, Green Circle, and White Text Label]

So funktioniert es: Schritt für Schritt

  • Zeilen 15-16: Holt den 2D-Zeichenkontext vom Canvas-Element.
  • Zeilen 18-29: Zeichnet ein Rechteck, einen Bogenpfad (Kreis) und Text.

Kernkonzepte

  • Das Canvas-Element bietet pixelgenaues Immediate-Mode-Rendering.
  • Setze die Attribute width und height immer direkt am Canvas (nicht per CSS), um Verzerrungen zu vermeiden.

Häufiger Fehler: Canvas-Abmessungen über CSS statt width/height-Attribute setzen

CSS width/height streckt das Standard-Canvas von 300x150 Pixeln und erzeugt unscharfe Grafiken.

❌ Falsch
<canvas style="width: 600px; height: 300px;"></canvas> // Stretched & blurry!
✅ Richtig
<canvas width="600" height="300"></canvas>

Verwandte HTML-Tutorials & Compiler

HTML auf Compilra ausführen und testen

Führe dieses Code-Snippet mit vorab bereitgestellter Standardeingabe (stdin) in Compilras Cloud-Compiler aus.

HTML Online-Compiler