Summary -

In this topic, we described about the SVG Gradients with detailed example.

A gradient is a simple switch from one color to another. In addition, numerous color changes can be used to the similar element.

There are two major types of gradients in SVG and those are -

  • Linear
  • Radial

Linear gradient

The SVG element can support to produce a smooth surface of colors in a straight way which is called a linear SVG gradient. This must include an id attribute to describe it after. We can draw ellipse using <ellipse> tag and uses <linearGradient> tag to apply an SVG linear gradient.

The <linearGradient> element should be nested within a <defs> tag. The <defs> tag is brief for descriptions and contains description of special elements (such as gradients).

We can produce a perpendicular gradient as well as a parallel gradient. A New way is to produce a SVG gradient in the similar direction as how SVG is specified.

Syntax -

<linearGradient id="id" x1="x1-percentage" y1="y1-percentage"
        x2="x2-percentage" y2="y2-percentage"> 
  • x1 – Specifies x-axis beginning point of the SVG linear gradient.
  • y1 – Specifies y-axis beginning point of the SVG linear gradient.
  • x2 – Specifies x-axis ending point of the SVG linear gradient.
  • y2 – Specifies y-axis ending point of the SVG linear gradient.

Example -

Below example describes how to draw linear gradients from red to yellow.
<!DOCTYPE html>
<html>
	<body>
		<svg height="150" width="300">
			<defs>
				<linearGradient id="grad1" x1="0%" y1="0%" 
					x2="100%" y2="10%">
					<stop offset="0%" style="stop-color:red;
						stop-opacity:1;" />
					<stop offset="100%" style="stop-color:yellow;
						stop-opacity:1;" /> 
				</linearGradient>
			</defs>
			<ellipse cx="100" cy="70" rx="85" ry="50" 
				fill="url(#grad1)" />
		</svg>
	</body>
</html> 

Output-

Radial gradient

The <radialGradient> element must be nested within a <defs> tag. The <defs> tag is brief for descriptions and contains description of special elements (such as gradients).

Also, the radial gradient produces surfaces of colors in a spherical way. This component should also include an id attribute to describe it after.

  • x1 – Specifies x-axis base of the SVG radial gradient.
  • y1 – Specifies y-axis middle of the radial gradient.
  • x2 – Specifies x-axis central point of the radial gradient.
  • y2 - Specifies y-axis central point of the radial gradient.

Example -

Below example describes how to draw radial gradient from white to blue.
<!DOCTYPE html>
<html>
	<body>
		<svg height="150" width="300">
			<defs>
				<radialGradient id="grad2" cx="40%" cy="60%" r="50%"
					fx="40%" fy="60%">
					<stop offset="0%" style="stop-color:blue;
						stop-opacity:0" />
					<stop offset="100%" style="stop-color:blue;
						stop-opacity:1" />
				</radialGradient>
			</defs>
			<ellipse cx="100" cy="70" rx="85" ry="50" 
				fill="url(#grad2)" />
		</svg>
	</body>
</html>

Output-