SVG Patterns

You can use a pre-defined graphic object (pattern) to fill another object or stroke. Patterns in SVG are defined within <defs> element and then referenced with URI.

All patterns are defined by the <pattern> element. The <pattern> element has the following attributes:

  • id attribute set a unique ID used to reference the pattern.
  • x, y, width and heinght attributes indicate how the pattern tiles are placed and spaced. The default value is 0.
  • patternUnits attribute defines the coordinate system for attributes x, y, width, height. It has 2 values:
    • objectBoundingBox is set when the user coordinate system for attributes x, y, width and height is established using the bounding box of the element to which the pattern is applied.
    • userSpaceOnUse (default) is set when the user coordinate system for attributes x, y, width and height is established using the viewbox.
  • patternContentUnits defines the coordinate system for the contents of the <pattern>. This attribute has no effect if attribute viewBox is specified. The attribute has 2 values:
    • userSpaceOnUse (default) is set when the user coordinate system for the contents of the <pattern> element is the coordinate system that results from taking the current user coordinate system in place at the time when the <pattern> element is referenced.
    • objectBoundingBox is set when the user coordinate system for the contents of the <pattern> element is established using the bounding box of the element to which the pattern is applied.
  • patternTransform attribute contains the information about the transformations made to a pattern before it is applied.
  • xlink:href attribute references to a different pattern element from which attributes are inherited.

The <pattern> element is never rendered directly. You can use a pattern only referencing it using the fill and stroke properties.

Here is a simple example:

  <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 150 150">
  <defs>
	  <pattern id="MyPattern" x="0" y="0" width="30" height="30" patternUnits="userSpaceOnUse">
		  <circle cx="11" cy="11" r="8" fill="#9d1d20" stroke="black"/>
		  <circle cx="11" cy="11" r="4" fill="grey" stroke="black"/>
	  </pattern>
  </defs>
  <rect x="5" y="2" width="145" height="145" fill="url(#MyPattern)" stroke="black" stroke-width="2"/>
  </svg>		
							

Here is the resulring image: