apike.ca

Filling and Stroking Shapes in SVG

Most attributes of SVG shapes from lines to text to paths define shape, position and size. To render it and display it, we need to consider how to fill a vector shape's volume and how to stroke the vector shape's edge.

Fills

All vector shapes that aren't lines have a volume that can be filled with a color, gradient or pattern. The attribute to do this is fill which needs a paint value.

1
2
3
4
<!-- Fill Examples -->
<rect x="100" y="30" width="200" height="200" rx="10" ry="10" fill="blue" />
<rect x="400" y="30" width="200" height="200" rx="10" ry="10" fill="url(#fillGrad)" />
<rect x="700" y="30" width="200" height="200" rx="10" ry="10" fill="url(#adobeBricks)" />
Example 1. Types of fills. (Download)
Attribute
Values
Initial
Comments
fill
black
Interior Color
fill-opacity
(0.0-1.0)
1
Interior Color's % transparent. Values outside range clamped. (See: Opacity)
fill-rule
(nonzero | evenodd | inherit)
nonzero
nonzero - object fully filled.
evenodd - alternates across line boundaries. (See: Clip and fill rule)

Strokes

Vector shapes have edges that can be painted along. To paint this edge requires a second attribute as the edge of a vector shape has no volume. So, stroking an edge requires the paint and the width.

The stroke attribute (a color, gradient or pattern) defines the paint value for the stroke. The stroke-width defines the width. The stroke-dasharray attribute defines a repeating sequence of lengths to go before switching stroking on and off. The last attribute is how to create dashed lines.

1
2
3
4
5
6
<!-- Stroke Examples -->
<circle cx="160" cy="120" r="90" fill="none" stroke="blue" stroke-width="30" />
<circle cx="500" cy="120" r="70" fill="none" stroke="blue" stroke-width="80" stroke-dasharray="3,6,8,11" />
<line x1="700" y1="210" x2="950" y2="210" stroke="blue" stroke-width="40" stroke-dasharray="7,3" />
<line x1="700" y1="210" x2="950" y2="210" stroke="green" stroke-width="40" stroke-dasharray="11,7" />
<line x1="700" y1="210" x2="950" y2="210" stroke="lightgreen" stroke-width="40" stroke-dasharray="4,7" />
Example 2. Strokes and stroke dash arrays. Strokes are centered. (Download)
Attribute
Values
Initial
Comments
stroke
none
Color of the object's outline.
stroke-width
(length | inherit)
1
Width of the object's outline.
stroke-opacity
(0.0-1.0)
1
Outline Color's % transparent. Values outside range clamped. (See SVG Opacity)
stroke-dasharray
(none | dasharray | inherit)
none
Makes the stroke dashed. "dasharray" is a list of (nonnegative) lengths separated by commas which alternates the stroke on and off.
stroke-dashoffset
(length | inherit)
0
Offset the dashes by a set length

As noted above, strokes are centred on the edge. The morphology filter can be used to create outside and inside strokes.