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.
๐ถ Most basic example
The <path> element lets you 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 looks like a line chart already!
As you can see, the <path> element expects a required d attribute. This attribute defines the shape of the path. Its syntax is a bit... obscure, to say the least. Let's find out how it works.
๐ 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:
Remember that the coordinate system starts from the top-left in SVG!
M0 105: moves the starting point of the path to coordinates0, 105. (Mstands for move to)L100 200: draws a straight line from the current point (0, 105) to the point (100, 200). (Lstands for line to)200 200: draws another straight line to (200, 200). Notice there's noLhere โ when you omit the command letter, SVG repeats the previous one implicitly.
Now, experiment with some changes in the sandbox below to get a better understanding of how it works:
Oh no! ๐ฑ
It seems like you haven't enrolled in the course yet!
Join many other students today and learn how to create bespoke, interactive graphs with d3.js and React!
Enrollment is currently closed. Join the waitlist to be notified when doors reopen:
Or Login