How SVG Handles Clipping Paths, Gradients, and Patterns
Scalable Vector Graphics (SVG) represents advanced graphical
techniques like clipping paths, gradients, and pattern fills using
declarative XML elements. These features are typically defined within a
<defs> (definitions) block with unique
id attributes, allowing them to be stored and referenced
multiple times across the document. Other graphical elements apply these
definitions using presentation attributes such as clip-path
or fill combined with functional url(#id)
syntax.
Clipping Paths
A clipping path restricts the visible region of an SVG element. It is
defined using the <clipPath> element, which encloses
one or more basic shapes, paths, or text elements that describe the
clipping boundary.
<svg viewBox="0 0 100 100">
<defs>
<clipPath id="circleClip">
<circle cx="50" cy="50" r="40" />
</clipPath>
</defs>
<rect x="0" y="0" width="100" height="100" fill="blue" clip-path="url(#circleClip)" />
</svg>When clip-path="url(#circleClip)" is applied to an
element, any part of that element falling outside the designated
<circle> area is completely hidden. The geometry
inside <clipPath> serves purely as an outline mask
and ignores styling attributes like color or stroke.
Gradients
SVG provides two types of smooth color transitions: linear gradients and radial gradients.
- Linear Gradients
(
<linearGradient>): Defined along a straight line between starting coordinates(x1, y1)and ending coordinates(x2, y2). - Radial Gradients
(
<radialGradient>): Defined by a center point(cx, cy), a radius(r), and an optional focal point(fx, fy).
Both gradient types use nested <stop> elements to
assign colors (stop-color) and opacities
(stop-opacity) at specific relative positions
(offset from 0% to 100%).
<svg viewBox="0 0 100 100">
<defs>
<linearGradient id="linearGrad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#ff0000" />
<stop offset="100%" stop-color="#0000ff" />
</linearGradient>
</defs>
<rect width="100" height="100" fill="url(#linearGrad)" />
</svg>Gradients are rendered onto target shapes by setting
fill="url(#gradientId)" or
stroke="url(#gradientId)".
Pattern Fills
The <pattern> element creates repeated, tileable
vector or raster graphics across a surface. A pattern defines its own
internal coordinate space via width, height,
and optional viewBox attributes.
<svg viewBox="0 0 100 100">
<defs>
<pattern id="dotPattern" width="20" height="20" patternUnits="userSpaceOnUse">
<circle cx="10" cy="10" r="4" fill="black" />
</pattern>
</defs>
<rect width="100" height="100" fill="url(#dotPattern)" />
</svg>The patternUnits attribute controls how the pattern
tiles across the surface—either based on the current user coordinate
system (userSpaceOnUse) or relative to the bounding box of
the target shape (objectBoundingBox). The target shape
applies the tiled pattern by referencing its identifier inside the
fill or stroke attribute.