Home > Articles

Painting

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Creating Patterns

The pattern element allows you to define a graphic element (or group of elements) as a repeatable pattern. Rather than duplicating the element multiple times, the pattern element reduces the number of code lines needed to perform the same task. The savings are two-fold:

  • Your file is easier to manage and peruse

  • Your file size is dramatically reduced

Using a pattern requires a pattern element surrounding the content to be tiled. This element has several characteristics that define how the tiled content will be displayed. The x and y attributes determine the top left-most position of the first tiled object within the object using the tile. The width and height properties define the respective distances between the top left-most edge of the first tiled object and its neighboring objects.

To apply the pattern, add the style rule fill:url(#PatternID), where PatternID is the name of the pattern's id value.

To try out the pattern element, you can take a break from the news center example. Instead, using Listing 7.8 as a guide, create a large rectangle in your SVG document (line 17).

Next, create a pattern element (line 13), and name the element with the id attribute. Then, give both the x and y attributes a value of 0 so that the object to be tiled starts in the very top-left corner of the applied object. Give both the width and height attributes a value of 25 so the object is repeated equidistant along each axis.

With the pattern element created, you will need to define its tiling content: a 10-by-10, blue-filled square (described on line 14). Line 8 shows the style rule needed to apply the pattern to the rectangle you created (line 17). Figure 7.10 shows the result.

Listing 7.8 Creating a Pattern Fill

01: <?xml version="1.0" standalone="no"?>
02: <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN
      "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
03:
04: <svg width="500" height="300">
05:
06: <style type="text/css">
07:   <![CDATA[
08:     .FillBoxPattern{fill:url(#BoxPattern);}
09:     .Fill99CCFF{fill:#99CCFF;}
10:   ]]>
11: </style>
12:
13:   <pattern id="BoxPattern" x="0" y="0" width="25" height="25" patternUnits="userSpaceOnUse">
14:     <rect x="0" y="0" width="10" height="10" class="Fill99CCFF"/>
15:   </pattern>
16:
17:   <rect id="BoxPatternBox" class="FillBoxPattern" x="0" y="0" width="500" height="300"/>
18:
19: </svg>

Figure 7.10 A repeating object can be made using the pattern element.

  • + Share This
  • 🔖 Save To Your Account