SVGBasics

Creating Paths with SVG

A path is an element that describes a set of lines, curves and arcs. A path can be stroked or used as input for other elements.

A path can be used to describe the same figures as line, polyline, polygon circle and rect elements. The syntax is a little more complex than those elements, but is also more general. The significant attribute in the path element called 'd'. The 'd' attribute is assigned a string of text which describes the path to be created. The instructions are reminiscent of the logo programming language or any number of other vector drawing instructions. The instructions are variations on move (without drawing), draw line, draw curve and draw arc. Each command is one letter followed by parameters. Whitespace is optional except between numeric parameters. First I'll give a simple example, then I'll explain how to write a string for the 'd' attribute.

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg viewBox = "0 0 1100 400" version = "1.1">
    <path id = "s3" d = "M 60 0 L 120 0 L 180 60 L 180 120 L 120 180 L 60 180 L 0 120 L 0 60" fill = "green" stroke = "black" stroke-width = "3"/>
</svg>

Where to begin - moveto and lineto

moveto

The moveto command is given by the single letter 'M' or 'm'. The uppercase 'M' takes absolute coordinates (for the current coordinate system) and the lowercase takes relative coordinates. Relative in this case means relative to the position that the last command finished drawing (also called the "current point"). The uppercase/lowercase distinction also applies to all the other drawing commands for the path element.

The moveto command is given at the start of the path description. No line is drawn when 'M' is processed. It can also be given later on while drawing for discontinuous lines.

lineto

Straight lines are drawn with "L", the lineto command. A straight line from the current location can be drawn with the lowercase equivalent "l". "L" is followed by a point, as in "L 200 400". Horizontal and vertical lines can be drawn with "H" and "V" followed by an x or y coordinate.

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg viewBox = "0 0 1100 400" version = "1.1">
    <!-- A triangle with absolute coordinates -->
    <path d = "M 200 50 L 300 150 L 200 150 L 200 50" stroke = "red" stroke-width = "3" fill = "none"/>
    <!-- A triangle with relative coordinates -->
    <path d = "M 500 50 l 100 100 l -100 0 l 0 -100" stroke = "green" stroke-width = "3" fill = "none"/>
    <!-- Practical use of relative moves -->
    <path d = "M 700 50 l 100 100 m 0 -100 l 100 100 m 0 -100 l 100 100" stroke = "blue" stroke-width = "3"/>
</svg>
©2004 Late Night PC Service | About Us | Site Map | Contact Us