# HTML5 Canvas - Dokumentation ## Überblick Das HTML5 Canvas-Element ermöglicht es, dynamische Grafiken, Animationen und interaktive Visualisierungen direkt im Browser zu erstellen. Es funktioniert wie eine digitale Leinwand, auf der mit JavaScript gezeichnet werden kann. ## Grundlagen ### Canvas-Element erstellen ```html <canvas id="myCanvas" width="800" height="600"></canvas> ``` ### JavaScript-Zugriff ```javascript const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); ``` **Wichtige Punkte:** - Canvas ist ein HTML-Element mit definierten Dimensionen - `getContext('2d')` gibt das Zeichenobjekt zurück - Alle Zeichenoperationen erfolgen über den Context ## Koordinatensystem ### Achsen-Orientierung ``` (0,0) ────────────────► X-Achse │ │ │ │ │ ▼ Y-Achse ``` **Koordinaten-Eigenschaften:** - **Ursprung (0,0)**: Oben links - **X-Achse**: Verläuft nach rechts (horizontal) - **Y-Achse**: Verläuft nach unten (vertikal) - **Einheit**: Pixel ### Positionsbeispiele ```javascript // Punkt oben links ctx.fillRect(0, 0, 50, 50); // Punkt oben rechts ctx.fillRect(750, 0, 50, 50); // Punkt unten links ctx.fillRect(0, 550, 50, 50); // Punkt unten rechts ctx.fillRect(750, 550, 50, 50); // Zentrum ctx.fillRect(375, 275, 50, 50); ``` ## Grundlegende Zeichenfunktionen ### Rechtecke zeichnen ```javascript // Gefülltes Rechteck ctx.fillStyle = 'blue'; ctx.fillRect(x, y, width, height); // Rechteck-Umriss ctx.strokeStyle = 'red'; ctx.lineWidth = 2; ctx.strokeRect(x, y, width, height); // Rechteck löschen ctx.clearRect(x, y, width, height); ``` ### Linien zeichnen ```javascript // Linie von Punkt A zu Punkt B ctx.beginPath(); ctx.moveTo(50, 50); // Startpunkt ctx.lineTo(200, 150); // Endpunkt ctx.strokeStyle = 'green'; ctx.lineWidth = 3; ctx.stroke(); ``` ### Kreise und Bögen ```javascript // Vollkreis ctx.beginPath(); ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI); ctx.fillStyle = 'orange'; ctx.fill(); // Halbkreis ctx.beginPath(); ctx.arc(centerX, centerY, radius, 0, Math.PI); ctx.strokeStyle = 'purple'; ctx.stroke(); ``` ## Pfade und komplexe Formen ### Pfad-Konzept ```javascript // Pfad starten ctx.beginPath(); // Verschiedene Pfad-Operationen ctx.moveTo(100, 100); // Startpunkt ohne Linie ctx.lineTo(200, 100); // Linie zum Punkt ctx.lineTo(150, 200); // Weitere Linie ctx.closePath(); // Pfad schließen // Pfad rendern ctx.fillStyle = 'yellow'; ctx.fill(); ctx.strokeStyle = 'black'; ctx.stroke(); ``` ### Kurven zeichnen ```javascript // Quadratische Kurve ctx.beginPath(); ctx.moveTo(50, 50); ctx.quadraticCurveTo(100, 25, 150, 50); ctx.stroke(); // Kubische Kurve ctx.beginPath(); ctx.moveTo(50, 100); ctx.bezierCurveTo(75, 50, 125, 150, 150, 100); ctx.stroke(); ``` ## Styling und Eigenschaften ### Farben und Stile ```javascript // Füllfarbe ctx.fillStyle = 'red'; ctx.fillStyle = '#ff0000'; ctx.fillStyle = 'rgb(255, 0, 0)'; ctx.fillStyle = 'rgba(255, 0, 0, 0.5)'; // Strichfarbe und -breite ctx.strokeStyle = 'blue'; ctx.lineWidth = 5; // Strichstil ctx.lineCap = 'round'; // round, butt, square ctx.lineJoin = 'round'; // round, bevel, miter ``` ### Gradients ```javascript // Linearer Gradient const gradient = ctx.createLinearGradient(0, 0, 200, 0); gradient.addColorStop(0, 'red'); gradient.addColorStop(0.5, 'yellow'); gradient.addColorStop(1, 'blue'); ctx.fillStyle = gradient; ctx.fillRect(0, 0, 200, 100); ``` ## Text auf Canvas ### Text zeichnen ```javascript // Text-Eigenschaften ctx.font = '30px Arial'; ctx.fillStyle = 'black'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; // Text rendern ctx.fillText('Hello Canvas!', 400, 300); ctx.strokeText('Umriss Text', 400, 350); ``` ## Transformationen ### Koordinatensystem verschieben ```javascript // Canvas-Zustand speichern ctx.save(); // Transformationen ctx.translate(100, 100); // Verschiebung ctx.rotate(Math.PI / 4); // Rotation (45 Grad) ctx.scale(2, 2); // Skalierung // Zeichnen (mit Transformationen) ctx.fillRect(0, 0, 50, 50); // Zustand wiederherstellen ctx.restore(); ``` ## Praktisches Beispiel ### Einfaches Zeichenprogramm ```javascript const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); let isDrawing = false; let lastX = 0; let lastY = 0; canvas.addEventListener('mousedown', (e) => { isDrawing = true; lastX = e.offsetX; lastY = e.offsetY; }); canvas.addEventListener('mousemove', (e) => { if (!isDrawing) return; ctx.beginPath(); ctx.moveTo(lastX, lastY); ctx.lineTo(e.offsetX, e.offsetY); ctx.strokeStyle = 'black'; ctx.lineWidth = 2; ctx.stroke(); lastX = e.offsetX; lastY = e.offsetY; }); canvas.addEventListener('mouseup', () => { isDrawing = false; }); ``` ## Animationen ### Grundlegendes Animations-Pattern ```javascript function animate() { // Canvas löschen ctx.clearRect(0, 0, canvas.width, canvas.height); // Objekt-Position aktualisieren x += deltaX; y += deltaY; // Objekt zeichnen ctx.fillStyle = 'red'; ctx.fillRect(x, y, 50, 50); // Nächsten Frame anfordern requestAnimationFrame(animate); } // Animation starten animate(); ``` ## Wichtige Konzepte ### Canvas vs. DOM - **Canvas**: Bitmap-basiert, gezeichnete Elemente sind nicht einzeln manipulierbar - **DOM**: Vektor-basiert, jedes Element ist ein Objekt - **Performance**: Canvas besser für komplexe Grafiken und Animationen ### Responsive Canvas ```javascript function resizeCanvas() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; } window.addEventListener('resize', resizeCanvas); resizeCanvas(); ``` ### Pixel-Manipulation ```javascript // Pixel-Daten abrufen const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); const data = imageData.data; // Pixel-Daten ändern (RGBA-Format) for (let i = 0; i < data.length; i += 4) { data[i] = 255; // Rot data[i + 1] = 0; // Grün data[i + 2] = 0; // Blau data[i + 3] = 255; // Alpha } // Pixel-Daten zurückschreiben ctx.putImageData(imageData, 0, 0); ``` ## Anwendungsbereiche - **Spiele**: 2D-Spiele und Spielgrafiken - **Datenvisualisierung**: Diagramme und Graphen - **Bildbearbeitung**: Filter und Effekte - **Animationen**: Interaktive Animationen - **Zeichenapps**: Mal- und Zeichenprogramme - **Simulationen**: Physik- und Mathematiksimulationen