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:
beginPath()– Starts a new path, clearing any previous path datamoveTo(x, y)– Lifts your "pen" and moves to a starting position without drawinglineTo(x, y)– Draws a straight line from the current position to the new coordinatesclosePath()– Draws a line back to the starting point, closing the shape- Finally, call
stroke()orfill()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.