Gradients
Basic application of SVG Linear and Radial Gradients to SVG Elements
Updated: 03 September 2023
For reference take a look at the MDN SVG Gradient Docs
SVG has provides us with two different gradient elements, namely linearGradient
and radialGradient
which can be applied as fills or strokes to SVG elements
Gradients work by defining them inside of a defs
element so that they can be reused in multiple parts of an SVG and they must have an id
attribute so they can be referenced by other elements
Defining Gradients
The stop
Element
When defining any type of gradient it’s necessary to define a stop
s. A stop
defines a color and it’s position and is always a child of a linearGradient
or radialGradient
element
A stop has the following properties:
offset
- where the stop should be placed along the gradient. Can either be a number of a percentage,offset="0.5"
oroffset="50%"
for example. Default is0
stop-color
- The color associated with the stop. Default isblack
stop-opacity
- The opacity associated with the stop Default is1
A gradient does not need to define all of the above properties but you likely will want to in order to effectively define a gradient
Some examples of a stop
using the above definitions can be seen below:
The linearGradient
Element
Linear gradients are gradients that change along a straight line (the gradient vector).
Creating a linearGradient
in the defs
section of an SVG file looks like so:
Additionally we can control the position/direction of the gradient vector by changing it’s start and end points using the x1
, x2
, y1
, and y2
values.
So a horizontal gradient (the default) would look something like this:
And a vertical one like so:
The radialGradient
Element
Radial Gradients are gradients that change along a a radius from a defined focal point
Creating a radialGradient
in the defs
section of an SVG file looks like so:
For a radialGradient
we can also control the radius, center point positions, and focal point radius, and focal point positions using r
, cx
, cy
, fr
, fx
, and fy
respectively
To define a gradient with a small center radius, we can do something like this:
Or for a gradient which is off-center we can do this:
And likewise for changing the focal point:
Or using fr
instead:
Using Gradients
Using SVG Gradients can be done by referencing the gradient from the fill
or stroke
property of an SVG element
For example, I can use the linearGradient
defined above for a circle’s fill with:
Or for the stroke on a path with:
A more complete example using the linearGradient
and radialGradient
can be seen below:
And the result: