Lesson 14 of 55 · HTML
Canvas 2D API – Shapes and Paths
Duration: 10 min
Drawing with Paths
<canvas id='canvas2' width='200' height='200'></canvas>
<script>
const c = document.getElementById('canvas2').getContext('2d');
c.beginPath();
c.moveTo(50, 20);
c.lineTo(150, 20);
c.lineTo(150, 120);
c.closePath(); // triangle
c.fillStyle = 'rgba(0,150,255,0.5)';
c.fill();
c.strokeStyle = '#003366';
c.stroke();
</script>
Path methods
beginPath(),moveTo(),lineTo(),arc(),closePath()build complex shapes.fill(),stroke()render the path.fillStyle,strokeStyle,lineWidthcontrol appearance.save()/restore()let you push/pop drawing state (color, transform, etc.).arcTo(),quadraticCurveTo(),bezierCurveTo()for curves.
Example: Rounded rectangle
c.beginPath();
c.moveTo(20, 10);
c.lineTo(180, 10);
c.quadraticCurveTo(190, 10, 190, 20);
c.lineTo(190, 90);
c.quadraticCurveTo(190, 100, 180, 100);
c.lineTo(20, 100);
c.quadraticCurveTo(10, 100, 10, 90);
c.lineTo(10, 20);
c.quadraticCurveTo(10, 10, 20, 10);
c.closePath();
c.fill();
Tip: Always call
beginPath()before starting a new shape to avoid unintentionally connecting to the previous path.
Quick checklist for path drawing
beginPath()called before each new shape? ✅- Stroke and fill styles set as needed? ✅
save()/restore()used when changing state temporarily? ✅- Curves used where appropriate for smoother shapes? ✅
- Path isolation maintained to prevent accidental connections? ✅
If any answer is “no”, refactor the drawing code.