The path element


In this lesson, we'll dive into one of the most versatile and powerful elements in SVG: the <path> element.

The <path> element allows you to create complex shapes and lines that go beyond the basic geometric shapes. It is essential to build some graph types like an area chart or a line chart.

Free
4 minutes read

Most basic example

The <path> element allows to draw literally any shape in the SVG area.

You provide it with a series of drawing commands that will make straight or curved lines, resulting in your final shape.

Let's check a basic example:

<svg height="300" width="400">
  <path
    d="M0 105 L100 200 L200 200 L300 20 L350 120"
    fill="none"
    stroke="#69b3a2"
  />
</svg>

This will result in the following shape:

Nice! This almost look like a line chart already!

As you can see the <path> element expect a required d attribute. This attribute defines the shape of the path. Let's discover its syntax.

Understanding the d Attribute

The d attribute defines the shape and outline of the path by specifying a series of drawing commands.

Each command consists of a letter that represents the type of drawing action (such as M for Move To) followed by one or more numbers that define the coordinates or control points.

Here is a breakdown of the svg path above:

  • M0 105: moves the starting point of the path to coordinates 0, 105. (M stands for move to)
  • L100 200: draws a straight line from the current point (0, 105) to the point (100, 200). (L stands for line to)
  • 200 200: draws a new straight line from the current point to the point (200, 200).

Now, experiment with some changes in the sandbox below to get a better understanding of how it works:

The good news 🎁

You won’t need to manually write the d attribute yourself. Understanding its role is helpful, but in practice, you'll rely on d3.js helper functions to generate paths for you.

These functions take your data and automatically convert it into the appropriate path data.

This is one of the reasons why d3.js is so powerful and beloved for data visualization! πŸ’™

Exercises