En snabbreferens för HTML5 Canvas 2D Rendering Context API (CanvasRenderingContext2D).
Hämta kontext
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
Grundformer & fyllningar
// Färg- och linjestilar
ctx.fillStyle = '#ff0000';
ctx.strokeStyle = '#0000ff';
ctx.lineWidth = 4;
ctx.lineCap = 'round'; // 'butt' | 'round' | 'square'
// Rektanglar: x, y, bredd, höjd
ctx.fillRect(10, 20, 200, 100);
ctx.strokeRect(10, 20, 200, 100);
ctx.clearRect(0, 0, canvas.width, canvas.height);
Banor (Paths) & anpassade former
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.lineTo(100, 150);
ctx.closePath();
ctx.fill();
ctx.stroke();
Bågar & cirklar
// arc(x, y, radius, startAngle, endAngle, counterClockwise)
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2, false);
ctx.stroke();
Tillståndsstack (Save & Restore)
ctx.save(); // Sparar aktuellt tillstånd på stacken
// Modifiera fillStyle, transformationer, skuggor...
ctx.restore(); // Återställer föregående tillstånd från stacken
Sparat tillstånd omfattar: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation och aktuell transformationsmatris.
Koordinattransformationer
ctx.translate(dx, dy);
ctx.rotate(angleInRadians);
ctx.scale(scaleX, scaleY);
// Rotera runt en godtycklig punkt (ox, oy)
ctx.translate(ox, oy);
ctx.rotate(angle);
ctx.translate(-ox, -oy);
Rita bilder
const img = new Image();
img.onload = () => {
// Rita hela bilden vid (x, y)
ctx.drawImage(img, 0, 0);
// Skalad bild: (img, dx, dy, dWidth, dHeight)
ctx.drawImage(img, 0, 0, 150, 100);
// Beskuren bild: (img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
ctx.drawImage(img, 50, 50, 100, 100, 0, 0, 100, 100);
};
img.src = 'picture.jpg';
Animationsloop-mönster
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Rendera bildruteelement...
requestAnimationFrame(draw);
}
requestAnimationFrame(draw);