Een beknopte handleiding voor de HTML5 Canvas 2D Rendering Context API (CanvasRenderingContext2D).
Context ophalen
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
Basisvormen & vullingen
// Kleur- en lijnstijlen
ctx.fillStyle = '#ff0000';
ctx.strokeStyle = '#0000ff';
ctx.lineWidth = 4;
ctx.lineCap = 'round'; // 'butt' | 'round' | 'square'
// Rechthoeken: x, y, breedte, hoogte
ctx.fillRect(10, 20, 200, 100);
ctx.strokeRect(10, 20, 200, 100);
ctx.clearRect(0, 0, canvas.width, canvas.height);
Paden & aangepaste vormen
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.lineTo(100, 150);
ctx.closePath();
ctx.fill();
ctx.stroke();
Bogen & cirkels
// arc(x, y, radius, startAngle, endAngle, counterClockwise)
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2, false);
ctx.stroke();
Statusstack (Save & Restore)
ctx.save(); // Slaat huidige status op de stack op
// Wijzig fillStyle, transformaties, schaduwen...
ctx.restore(); // Herstelt vorige status van de stack
De opgeslagen status omvat: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation en de huidige transformatiematrix.
Coördinatentransformaties
ctx.translate(dx, dy);
ctx.rotate(angleInRadians);
ctx.scale(scaleX, scaleY);
// Roteer rond een willekeurige oorsprong (ox, oy)
ctx.translate(ox, oy);
ctx.rotate(angle);
ctx.translate(-ox, -oy);
Afbeeldingen tekenen
const img = new Image();
img.onload = () => {
// Teken volledige afbeelding op (x, y)
ctx.drawImage(img, 0, 0);
// Geschaald: (img, dx, dy, dWidth, dHeight)
ctx.drawImage(img, 0, 0, 150, 100);
// Uitsnede tekenen: (img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
ctx.drawImage(img, 50, 50, 100, 100, 0, 0, 100, 100);
};
img.src = 'picture.jpg';
Animatielus-patroon
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Frame-elementen renderen...
requestAnimationFrame(draw);
}
requestAnimationFrame(draw);