SVG Patterns
By mbystedt on Feb 27, 2014, 6:56:43 PM
Creating a pattern is like creating a small SVG document. You define the coordinates you want the view to show and the size of the view. Then you add shapes into your pattern. The pattern repeats when an edge of the view box (viewing area) is hit. Any shapes outside of your pattern's view box are clipped (removed) by default. Like a gradient, you have to define a pattern before you create something which uses it.
<defs> <pattern id="checkerPattern" patternUnits="userSpaceOnUse" x="0" y="0" width="20" height="20" viewBox="0 0 10 10" > <rect x="0" y="0" width="5" height="5" fill="lightblue" /> <rect x="5" y="5" width="5" height="5" fill="lightblue" /> </pattern> </defs> <!-- Background --> <rect x="0" y="0" width="100%" height="100%" fill="url(#checkerPattern)" />
Code 1. A simple pattern. This is the background used in many of the examples.
That's a pretty simple pattern and that's all there is to it. The contents of the pattern are "drawn" relative to the new coordinate system you create. The pattern is never drawn directly and always referenced so it should be placed in a 'defs' tag.
<pattern>
Attribute |
Explanation |
id |
The unique id required to reference this pattern. |
patternUnits |
'userSpaceOnUse' or 'objectBoundingBox'. The second value makes units of x, y, width, height a fraction (or percentage) of the object bounding box which uses the pattern. |
patternContentUnits |
'userSpaceOnUse' or 'objectBoundingBox' |
patternTransform |
Allows the whole pattern to be transformed. See: Tranformations |
x |
Pattern's offset from the top-left corner. (default 0) |
y |
Pattern's offset from the top-left corner. (default 0) |
width |
The width of the pattern tile. (default 100%) |
height |
The height of the pattern tile. (default 100%) |
viewBox |
The view box is the points "seen" in this SVG drawing area. 4 values separated by white space or commas. (min x, min y, width, height) |
xlink:href |
Reference to another pattern whose attribute values are used as defaults and any childern are inherited. Recursive. |
Example 1. Snow falling on Geihoku. The pattern is animated by JavaScript. (Download)
Related Topics
The shapes inside a pattern can't be animated and they ignore all events. The shapes in the pattern will also ignore the 'display' attribute and always display. You can still reference the contents of a pattern and change them. Place your mouse over the example above! The pattern is animated from outside by using JavaScript.