SVG Path Tutorial

By Xah Lee. Date: . Last updated: .

This page is a tutorial on SVG path element.

The path element is the most powerful and useful element. It can effectively replace any other SVG shapes such as {rect, circle, line, polygon}.

Path element is also the most complex to understand. If you are scripting SVG with JavaScript, it's essential to understand the path element.

moveto, lineto

<svg width="100" height="100">
<path d="M 0 0 L 50 0 L 0 50 L 90 90"
style="stroke:black; fill:yellow; stroke-width:5" />
</svg>

Path's Default Stroke Style

Warning: By default, path's stroke style is none. So, you will need to add style="stroke:red" or similar. 〔►see SVG: Basic Shape Styles

Here's a example. You see the line is not visible.

<svg width="100" height="100">
<path d="M 0 0 L 50 50" />
</svg>

Here's a example of the same line, with style added.

<svg width="100" height="100">
<path d="M 0 0 L 50 50" style="stroke:blue" />
</svg>

〔►see SVG: Basic Shape Styles

lowercase = relative coordinate

<svg width="100" height="100">
<path d="m 50 0
l  8 5
l -8 5
l  8 5
l -8 5
l  8 5
l -8 5
l  8 5
l -8 5"
style="stroke:black; fill:yellow" />
</svg>

Lowercase command names mean use relative coordinates (relative to current point). So, here, we use l to zigzag. Each time, the y coordinate increases by 5, while x goes 8 to the right and -8 to the left.

Lowercase and uppercase commands can be mixed.

<svg width="100" height="100">
<path d="M 0 0 L 50 50 l 20 -10 l 10 30 m -10 5 l -20 8"
style="stroke:black; fill:none;" />
</svg>

z = close path

<svg width="100" height="100">
<path d="m 10 10 l 0 20 l 30 30 z"
style="stroke:black; fill:yellow" />
</svg>

Paths – SVG 1.1 (Second Edition)#PathDataClosePathCommand

Shortcut Notation for Horizontal Line, Vertical Line

Horizontal line has a shortcut notation. Instead of L 30 0, you can write H 30. Similarly for vertical lines.

<svg width="100" height="100">
<path d="M 10 10 h 10 v 10 h 10 v 10 h 10 v 10"
style="stroke:black; fill:yellow" />
</svg>

Shortcut Notations, Comma, Redundant Spaces

Redundant space between command letter or before negative number can be omitted. Example:

Elliptical Arcs

SVG Path: Elliptical Arc

Quadratic Bezier Curve

Quadratic bezier curve has just 1 control point.

<svg width="100" height="100">
<path d="M 0 0 Q 100 0 , 100 100"
style="stroke:black; fill:yellow" />
</svg>
<svg width="100" height="100">
<path d="M 0 0 Q 100 0 , 50 50 T 100 100"
style="stroke:black; fill:yellow" />
</svg>

Paths – SVG 1.1 (Second Edition)#PathDataQuadraticBezierCommands

Cubic Bezier Curve

Cubic bezier curve has 2 control points.

<svg width="100" height="100">
<path d="M 0 0 C 100 0, 0 100, 100 100"
 style="stroke:black; fill:yellow" />
</svg>

Paths – SVG 1.1 (Second Edition)#PathDataCubicBezierCommands

Reference

Paths – SVG 1.1 (Second Edition)

Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.