How to Create Path in SVG: Syntax and Examples
To create a path in SVG, use the
<path> element with the d attribute that defines the shape using commands like M (move), L (line), and Z (close path). The d attribute contains a series of instructions that tell the browser how to draw the shape.Syntax
The <path> element uses the d attribute to define the shape. The d attribute contains commands and coordinates:
- M x,y: Move to position (x,y) without drawing.
- L x,y: Draw a line from the current point to (x,y).
- Z: Close the path by drawing a line back to the start.
Commands can be uppercase (absolute positions) or lowercase (relative positions).
html
<path d="M10 10 L90 10 L90 90 L10 90 Z" />Example
This example draws a simple square using the <path> element with the d attribute commands.
html
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg" aria-label="Square path example" role="img"> <path d="M10 10 L90 10 L90 90 L10 90 Z" fill="lightblue" stroke="blue" stroke-width="2" /> </svg>
Output
A light blue square with a blue border inside a 100x100 SVG canvas.
Common Pitfalls
Common mistakes when creating SVG paths include:
- Forgetting to close the path with
Zwhen needed, which leaves the shape open. - Mixing uppercase and lowercase commands without understanding absolute vs relative positions.
- Incorrect coordinate values causing unexpected shapes.
Always check your coordinates and use a tool or browser DevTools to preview your SVG.
html
<!-- Wrong: path not closed --> <path d="M10 10 L90 10 L90 90 L10 90" fill="none" stroke="red" /> <!-- Right: path closed with Z --> <path d="M10 10 L90 10 L90 90 L10 90 Z" fill="none" stroke="green" />
Output
The first path is an open shape with red stroke; the second is a closed shape with green stroke.
Quick Reference
| Command | Description | Example |
|---|---|---|
| M | Move to (start point) | M10 10 |
| L | Draw line to | L90 10 |
| H | Horizontal line to | H50 |
| V | Vertical line to | V80 |
| Z | Close path | Z |
Key Takeaways
Use the element with the d attribute to create shapes in SVG.
Commands like M, L, and Z define moves, lines, and closing the path.
Uppercase commands use absolute coordinates; lowercase use relative.
Always close your path with Z if you want a closed shape.
Preview your SVG in a browser to catch coordinate or syntax errors.