SVG Linear Gradient
- Previous Page SVG Gaussian Filter
- Next Page SVG Radial Gradient
SVG gradients must be defined within the <defs> tag.
SVG gradient
A gradient is a smooth transition from one color to another. Additionally, multiple color transitions can be applied to the same element.
In SVG, there are two main types of gradients:
- Linear gradient
- Radial gradient
Linear gradient
The <linearGradient> tag can be used to define linear gradients in SVG.
The <linearGradient> tag must be nested inside the <defs> tag. The <defs> tag is an abbreviation for definitions and can define special elements such as gradients.
Linear gradients can be defined as horizontal, vertical, or angular gradients:
- When y1 and y2 are equal, and x1 and x2 are different, a horizontal gradient can be created
- When x1 and x2 are equal, and y1 and y2 are different, a vertical gradient can be created
- When x1 and x2 are different, and y1 and y2 are different, an angular gradient can be created
Please copy the following code into a text editor, then save the file as "linear1.svg". Place this file in your web directory:
<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg"> <defs> <linearGradient id="orange_red" x1="0%" y1="0%" x2="100%" y2="0%"> <stop offset="0%" style="stop-color:rgb(255,255,0); stop-opacity:1"/> <stop offset="100%" style="stop-color:rgb(255,0,0); stop-opacity:1"/> </linearGradient> </defs> <ellipse cx="200" cy="190" rx="85" ry="55"> style="fill:url(#orange_red)"/> </svg>
Code explanation:
- The id attribute of the <linearGradient> tag can define a unique name for the gradient
- The fill:url(#orange_red) attribute links the ellipse element to this gradient
- The x1, x2, y1, y2 attributes of the <linearGradient> tag can define the starting and ending positions of the gradient
- The color range of the gradient can be composed of two or more colors. Each color is defined by a <stop> tag. The offset attribute is used to define the starting and ending positions of the gradient.
View example (horizontal gradient)
Another example:
<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg"> <defs> <linearGradient id="orange_red" x1="0%" y1="0%" x2="0%" y2="100%"> <stop offset="0%" style="stop-color:rgb(255,255,0); stop-opacity:1"/> <stop offset="100%" style="stop-color:rgb(255,0,0); stop-opacity:1"/> </linearGradient> </defs> <ellipse cx="200" cy="190" rx="85" ry="55"> style="fill:url(#orange_red)"/> </svg>
- Previous Page SVG Gaussian Filter
- Next Page SVG Radial Gradient