SVG 线性渐变
SVG 渐变
渐变是从一种颜色到另一种颜色的平滑过渡。此外,可以将多种颜色过渡应用于同一元素。
SVG 中有两种主要的渐变类型:
- 线性渐变
- 放射渐变
SVG 线性渐变 - <linearGradient>
<linearGradient> 元素用于定义线性渐变。
<linearGradient> 元素必须嵌套在 <defs> 标记内。<defs> 元素是定义(definitions)的缩写,包含对特殊元素(比如滤镜)的定义。
线性渐变可以定义为水平、垂直或角度渐变:
- 当
y1和y2相等且x1和x2不相等时创建水平渐变 - 当
x1和x2相等且y1和y2不相等时创建垂直渐变 - 当
x1和x2不同并且y1和y2不相等时创建角度渐变
例子 1
定义一个椭圆,它有从黄色到红色的水平线性渐变:
这是 SVG 代码:
<svg height="150" width="400">
<defs>
<linearGradient id="grad1" 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="70" rx="85" ry="55" fill="url(#grad1)" />
</svg>
代码解释:
<linearGradient>标签的id属性定义了渐变的唯一名称<linearGradient>标签的x1、x2、y1、y2属性定义渐变的开始和结束位置- 渐变的颜色范围可以由两种或多种颜色组成。每种颜色都用
<stop>标记指定 offset属性用于定义渐变颜色的开始和结束位置fill属性将椭圆元素链接到渐变
例子 2
定义一个椭圆,它有从黄色到红色的垂直线性渐变:
这是 SVG 代码:
<svg height="150" width="400">
<defs>
<linearGradient id="grad2" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
</linearGradient>
</defs>
<ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad2)" />
</svg>
例子 3
定义一个椭圆,并在椭圆内添加文本,它有从黄色到红色的水平线性渐变的:
这是 SVG 代码:
<svg height="150" width="400">
<defs>
<linearGradient id="grad3" 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="70" rx="85" ry="55" fill="url(#grad3)" />
<text fill="#ffffff" font-size="45" font-family="Verdana" x="150" y="86">
SVG</text>
</svg>
代码解释:
<text>元素用于添加文本