Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Canvas 2D API – Shapes and Paths | HTML Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. HTML Course

Lesson 14 of 55

·HTML

Canvas 2D API – Shapes and Paths

10 min

Course progress25%

What you'll learn

Keep these ideas in mind as you work through the lesson.

5 points
  • Path construction methods (`beginPath`, `moveTo`, `lineTo`, `arc`, `quadraticCurveTo`, `bezierCurveTo`)
  • Filling and stroking paths with `fill()` and `stroke()`
  • Styling options (`fillStyle`, `strokeStyle`, `lineWidth`)
  • State management with `save()` and `restore()`
  • Best practice of isolating distinct shapes with `beginPath()`

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, lineWidth control 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

  1. beginPath() called before each new shape? ✅
  2. Stroke and fill styles set as needed? ✅
  3. save()/restore() used when changing state temporarily? ✅
  4. Curves used where appropriate for smoother shapes? ✅
  5. Path isolation maintained to prevent accidental connections? ✅

If any answer is “no”, refactor the drawing code.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from HTML CourseBrowse activities
Previous lessonCanvas BasicsContinue to lesson 15SVG BasicsBack to HTML Course curriculum