SVG linearGradient Coordinate Attributes
In Scalable Vector Graphics (SVG), the direction and length of a
linear gradient are determined by a linear gradient vector. This article
explains the exact attributes used to define the starting and ending
coordinates of an SVG <linearGradient>
element—specifically x1, y1, x2,
and y2—and how they dictate the angle, position, and
transition of the gradient fill across a shape.
The Four Coordinate Attributes
The starting and ending points of the gradient vector are controlled
by four primary attributes on the <linearGradient>
element:
x1: Defines the horizontal starting point (x-coordinate) of the gradient vector.y1: Defines the vertical starting point (y-coordinate) of the gradient vector.x2: Defines the horizontal ending point (x-coordinate) of the gradient vector.y2: Defines the vertical ending point (y-coordinate) of the gradient vector.
By default, if these attributes are omitted, SVG sets the vector to
x1="0%", y1="0%", x2="100%", and
y2="0%", producing a horizontal gradient that transitions
from left to right.
Coordinate Systems:
gradientUnits
The values assigned to x1, y1,
x2, and y2 are interpreted according to the
gradientUnits attribute, which accepts two values:
objectBoundingBox(Default): Coordinates are expressed as percentages (such as0%to100%) or decimal values (from0.0to1.0) relative to the bounding box of the element using the gradient. For example,x1="0%"represents the far-left edge of the element, whilex2="100%"represents the far-right edge.userSpaceOnUse: Coordinates represent absolute coordinate units within the current SVG viewport space (such as pixels). In this mode, coordinates do not automatically scale with the shape’s size.
Common Vector Configurations
Changing the combination of the four vector attributes changes the gradient’s direction:
- Horizontal (Left to Right):
x1="0%",y1="0%",x2="100%",y2="0%" - Horizontal (Right to Left):
x1="100%",y1="0%",x2="0%",y2="0%" - Vertical (Top to Bottom):
x1="0%",y1="0%",x2="0%",y2="100%" - Diagonal (Top-Left to Bottom-Right):
x1="0%",y1="0%",x2="100%",y2="100%" - Diagonal (Bottom-Left to Top-Right):
x1="0%",y1="100%",x2="100%",y2="0%"
By adjusting these four attributes, you have complete control over the trajectory, angle, and spread of any SVG linear gradient.