Code

Canvas

Basic Shapes

Beginner Draw rectangles, circles, lines, arcs, and polygons using the 2D rendering context. MDN Reference

const ctx = canvas.getContext('2d')!;

// Filled rectangle
ctx.fillStyle = '#4f46e5';
ctx.fillRect(20, 20, 120, 80);

// Stroked rectangle
ctx.strokeStyle = '#e11d48';
ctx.lineWidth = 3;
ctx.strokeRect(160, 20, 120, 80);

// Clear a region
ctx.clearRect(50, 40, 60, 40);

// Line
ctx.beginPath();
ctx.moveTo(20, 140);
ctx.lineTo(280, 140);
ctx.strokeStyle = '#16a34a';
ctx.lineWidth = 4;
ctx.stroke();

// Full circle
ctx.beginPath();
ctx.arc(80, 220, 50, 0, Math.PI * 2);
ctx.fillStyle = '#f59e0b';
ctx.fill();

// Semi-circle
ctx.beginPath();
ctx.arc(220, 220, 50, 0, Math.PI);
ctx.strokeStyle = '#0ea5e9';
ctx.lineWidth = 3;
ctx.stroke();

// Triangle
ctx.beginPath();
ctx.moveTo(320, 170);
ctx.lineTo(420, 270);
ctx.lineTo(220, 270);
ctx.closePath();
ctx.fillStyle = '#7c3aed';
ctx.fill();

// Rounded rectangle
ctx.beginPath();
ctx.roundRect(320, 20, 120, 80, 16);
ctx.fillStyle = '#db2777';
ctx.fill();
Key APIs
  • ctx.fillRect(x, y, w, h) — filled rectangle shortcut
  • ctx.strokeRect(x, y, w, h) — outlined rectangle shortcut
  • ctx.clearRect(x, y, w, h) — erase pixels back to transparent
  • ctx.arc(x, y, r, startAngle, endAngle) — full circles and arcs
  • ctx.moveTo / lineTo / closePath — arbitrary polygon paths
  • ctx.roundRect(x, y, w, h, radii) — CSS-style rounded corners