Canvas API Guide
Setup & Basic Drawing
const canvas = document.querySelector('#myCanvas');
const ctx = canvas.getContext('2d');
// Set canvas size (avoid CSS stretching)
canvas.width = 800;
canvas.height = 600;
// Rectangle
ctx.fillStyle = '#6c63ff';
ctx.fillRect(50, 50, 200, 100); // x, y, width, height
ctx.strokeStyle = '#fff';
ctx.lineWidth = 2;
ctx.strokeRect(50, 50, 200, 100);
ctx.clearRect(60, 60, 30, 30); // erase area
// Circle
ctx.beginPath();
ctx.arc(300, 150, 50, 0, Math.PI * 2); // cx, cy, radius, start, end
ctx.fillStyle = '#ff6363';
ctx.fill();
ctx.stroke();
Paths
// Line path
ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(200, 200);
ctx.lineTo(300, 100);
ctx.closePath();
ctx.stroke();
// Bezier curves
ctx.beginPath();
ctx.moveTo(50, 200);
ctx.bezierCurveTo(100, 100, 200, 100, 250, 200); // cp1x,cp1y,cp2x,cp2y,ex,ey
ctx.stroke();
// Rounded rectangle (roundRect)
ctx.beginPath();
ctx.roundRect(50, 50, 200, 100, 12); // x,y,w,h,radius
ctx.fill();
Text
ctx.font = 'bold 24px Inter, sans-serif';
ctx.fillStyle = '#ffffff';
ctx.textAlign = 'center'; // left | right | center | start | end
ctx.textBaseline = 'middle'; // top | middle | bottom | alphabetic
ctx.fillText('Hello Canvas', 400, 300);
ctx.strokeText('Outlined Text', 400, 350);
// Measure text
const metrics = ctx.measureText('Hello');
console.log(metrics.width); // pixel width
Transformations & Gradients
// Save/restore state
ctx.save();
ctx.translate(400, 300); // move origin
ctx.rotate(Math.PI / 4); // 45 degrees
ctx.scale(2, 2);
ctx.fillStyle = '#6c63ff';
ctx.fillRect(-50, -50, 100, 100);
ctx.restore(); // reset transform
// Linear gradient
const grad = ctx.createLinearGradient(0, 0, 400, 0);
grad.addColorStop(0, '#6c63ff');
grad.addColorStop(1, '#ff6363');
ctx.fillStyle = grad;
ctx.fillRect(0, 0, 400, 100);
// Radial gradient
const radial = ctx.createRadialGradient(200, 200, 10, 200, 200, 100);
radial.addColorStop(0, '#fff');
radial.addColorStop(1, 'rgba(108,99,255,0)');
Animation Loop
let x = 0;
function animate() {
// Clear frame
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw
ctx.fillStyle = '#6c63ff';
ctx.beginPath();
ctx.arc(x, 200, 30, 0, Math.PI * 2);
ctx.fill();
// Move
x = (x + 2) % canvas.width;
// Schedule next frame
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);