A quick reference guide to the HTML5 Canvas 2D rendering context API (CanvasRenderingContext2D).
Obtaining Context
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
Basic Shapes & Fills
// Color and line styles
ctx.fillStyle = '#ff0000';
ctx.strokeStyle = '#0000ff';
ctx.lineWidth = 4;
ctx.lineCap = 'round'; // 'butt' | 'round' | 'square'
// Direct rectangles: x, y, width, height
ctx.fillRect(10, 20, 200, 100);
ctx.strokeRect(10, 20, 200, 100);
ctx.clearRect(0, 0, canvas.width, canvas.height);
Paths & Custom Shapes
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.lineTo(100, 150);
ctx.closePath();
ctx.fill();
ctx.stroke();
Arcs & Circles
// arc(x, y, radius, startAngle, endAngle, counterClockwise)
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2, false);
ctx.stroke();
State Stack (Save & Restore)
ctx.save(); // Pushes current state to stack
// Modify fillStyle, transforms, clipping, shadows...
ctx.restore(); // Pops and restores previous state
Saved state includes: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, and current transformation matrix.
Coordinate Transformations
ctx.translate(dx, dy);
ctx.rotate(angleInRadians);
ctx.scale(scaleX, scaleY);
// Rotate around an arbitrary origin (ox, oy)
ctx.translate(ox, oy);
ctx.rotate(angle);
ctx.translate(-ox, -oy);
Image Drawing
const img = new Image();
img.onload = () => {
// Draw full image at (x, y)
ctx.drawImage(img, 0, 0);
// Scaled: (img, dx, dy, dWidth, dHeight)
ctx.drawImage(img, 0, 0, 150, 100);
// Cropped slice: (img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
ctx.drawImage(img, 50, 50, 100, 100, 0, 0, 100, 100);
};
img.src = 'picture.jpg';
Animation Loop Pattern
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Render frame elements...
requestAnimationFrame(draw);
}
requestAnimationFrame(draw);