Creating and Editing SVG Graphics

  • 7/15/2012

Creating Patterns

The SVG language helps you create and reuse patterns with ease. Patterns are extremely useful—in fact, the grid background found in many of this book’s examples is just a simple pattern that consists of a single 10-by-10-pixel rectangle. The <defs> element can be used to store content that will not be directly displayed. This stored hidden content can then be referenced and displayed by other SVG elements, which makes it ideal for things such as patterns that contain reusable graphics.

To create a basic pattern in SVG, first place a rectangle within a <pattern> element, and then put everything inside of a <defs> element.

<defs>
  <pattern id="Pattern01" width="10" height="10" patternUnits="userSpaceOnUse">
    <rect width="10" height="10" fill="#FFFFFF" stroke="#000000" stroke-width="0.1"/>
  </pattern>
</defs>

Now, to use this pattern anywhere in your SVG graphic, simply set your element’s fill attribute value to the id of the pattern, like this: url(#Pattern01).

<rect id="Background" x="0" y="0" width="100%" height="100%"
  fill="url(#Pattern01)" stroke-width="0.5" stroke="#000000" />