Lesson 14 of 55
HTMLCanvas 2D API – Shapes and Paths
10 min
Course progress25%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 14 of 55
HTML10 min
Keep these ideas in mind as you work through the lesson.
<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>
beginPath(), moveTo(), lineTo(), arc(), closePath() build complex shapes.fill(), stroke() render the path.fillStyle, strokeStyle, lineWidth control appearance.save() / restore() let you push/pop drawing state (color, transform, etc.).arcTo(), quadraticCurveTo(), bezierCurveTo() for curves.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.
beginPath() called before each new shape? ✅save()/restore() used when changing state temporarily? ✅If any answer is “no”, refactor the drawing code.