Chapter 11. Picture-Perfect Patterns

The word pattern evokes the repeating designs we explored in Chapter 10. However, the SVG <pattern> element is more flexible than this. By defining a pattern tile that fits the object bounding box, you can create a pattern that fills the entire shape without repeating.

Why would you want to do that? One reason is to be able to layer together multiple paint servers. Another is to fill a shape with an image, similar to a CSS background image.

As we have already mentioned briefly, SVG 2 will allow you to layer multiple paint servers in a single fill declaration, and use an image as a fill value directly, making these types of pattern redundant. Until those features are available, however, these techniques are essential to create many effects.

This chapter also examines the use of the viewBox and preserveAspectRatio attributes on the <pattern> element. These attributes are particularly important with full-image fills, but they can also be used with repeated patterns.

The Layered Look

In Example 9-8 at the end of Chapter 9, we created the effect of a spotlight on a stage by drawing three separate rectangles, each filled with a different gradient. This approach is fine for a single shape, but isn’t very useful if you want to use the same layering effect on multiple shapes. That’s where patterns come in. A pattern can contain all the layers, turning them into a single paint server for use by other shapes.

Example 11-1 uses three gradients combined ...

Get SVG Colors, Patterns & Gradients now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.