Course contentsShow
← Web Development
Lesson 2616 of 2,98247. Data VisualizationFree lesson

Drawing Paths

Creating complex shapes with beginPath, moveTo, lineTo, and closePath methods.

Drawing Paths

You'll learn how to create custom shapes on canvas using path methods to draw anything beyond simple rectangles.

What Are Paths?

Think of paths like drawing with a pen on paper: you place the pen down at a starting point, draw lines connecting various points, and optionally close the shape by connecting back to the start. In canvas, paths let you create complex shapes—triangles, polygons, stars, or any custom geometry your visualization needs.

The Core Path Methods

Every path drawing follows a pattern:

  1. beginPath() – Starts a new path, clearing any previous path data
  2. moveTo(x, y) – Lifts your "pen" and moves to a starting position without drawing
  3. lineTo(x, y) – Draws a straight line from the current position to the new coordinates
  4. closePath() – Draws a line back to the starting point, closing the shape
  5. Finally, call stroke() or fill() to make the path visible

Example Pattern

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// Draw a triangle
ctx.beginPath();
ctx.moveTo(100, 50);   // Move to top point
ctx.lineTo(150, 150);  // Draw to bottom-right
ctx.lineTo(50, 150);   // Draw to bottom-left
ctx.closePath();       // Connect back to start
ctx.stroke();          // Make it visible

This creates a triangle by moving to the top point, then drawing lines to form the shape, and closing it automatically.

Key Takeaway: Use beginPath() to start, moveTo() to position without drawing, lineTo() to draw connecting lines, and closePath() to complete shapes—essential for creating any custom geometry in data visualizations.