Una guida di riferimento rapido per l'API del contesto di rendering 2D HTML5 Canvas (CanvasRenderingContext2D).
Ottenere il contesto
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
Forme di base e riempimenti
// Stili di colore e linea
ctx.fillStyle = '#ff0000';
ctx.strokeStyle = '#0000ff';
ctx.lineWidth = 4;
ctx.lineCap = 'round'; // 'butt' | 'round' | 'square'
// Rettangoli diretti: x, y, larghezza, altezza
ctx.fillRect(10, 20, 200, 100);
ctx.strokeRect(10, 20, 200, 100);
ctx.clearRect(0, 0, canvas.width, canvas.height);
Tracciati e forme personalizzate
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.lineTo(100, 150);
ctx.closePath();
ctx.fill();
ctx.stroke();
Archi e cerchi
// arc(x, y, radius, startAngle, endAngle, counterClockwise)
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2, false);
ctx.stroke();
Stack degli stati (Save & Restore)
ctx.save(); // Salva lo stato corrente nello stack
// Modifica fillStyle, trasformazioni, ombreggiature...
ctx.restore(); // Ripristina lo stato precedente dallo stack
Lo stato salvato include: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation e la matrice di trasformazione corrente.
Trasformazioni di coordinate
ctx.translate(dx, dy);
ctx.rotate(angleInRadians);
ctx.scale(scaleX, scaleY);
// Ruotare attorno a un'origine arbitraria (ox, oy)
ctx.translate(ox, oy);
ctx.rotate(angle);
ctx.translate(-ox, -oy);
Disegno di immagini
const img = new Image();
img.onload = () => {
// Disegna l'immagine completa in (x, y)
ctx.drawImage(img, 0, 0);
// Disegno scalato: (img, dx, dy, dWidth, dHeight)
ctx.drawImage(img, 0, 0, 150, 100);
// Ritaglio e disegno: (img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
ctx.drawImage(img, 50, 50, 100, 100, 0, 0, 100, 100);
};
img.src = 'picture.jpg';
Pattern del ciclo di animazione
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Renderizza gli elementi del frame...
requestAnimationFrame(draw);
}
requestAnimationFrame(draw);