svg渐变 线性渐变和径向渐变

293 阅读1分钟

一、linearGradient 线性渐变

SVG 渐变必须在 标签中进行定义。

线性渐变可被定义为水平、垂直或角形的渐变:

  • 当 y1 和 y2 相等,而 x1 和 x2 不同时,可创建水平渐变
  • 当 x1 和 x2 相等,而 y1 和 y2 不同时,可创建垂直渐变
  • 当 x1 和 x2 不同,且 y1 和 y2 不同时,可创建角形渐变

属性

  • <linearGradient> 标签的 id 属性可为渐变定义一个唯一的名称
  • fill:url(#orange_red) 属性把 ellipse 元素链接到此渐变
  • <linearGradient> 标签的 x1、x2、y1、y2 属性可定义渐变的开始和结束位置
  • 渐变的颜色范围可由两种或多种颜色组成。每种颜色通过一个 标签来规定。offset 属性用来定义渐变的开始和结束位置。

示例

<svg width="100%" height="800">
    <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)" />
    
    <defs>
        <linearGradient id="orange_red1" 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="310" rx="85" ry="55" style="fill:url(#orange_red1)" />
    <defs>
        <linearGradient id="orange_red2" x1="0%" y1="0%" x2="100%" 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="430" rx="85" ry="55" style="fill:url(#orange_red2)" />
</svg>

渐变

二、radialGradient 径向渐变

属性

  • <radialGradient> 标签的 id 属性可为渐变定义一个唯一的名称,
  • fill:url(#grey_blue) 属性把 ellipse 元素链接到此渐变,
  • cx、cy 和 r 属性定义外圈,而 fx 和 fy 定义内圈 渐变的颜色范围可由两种或多种颜色组成。
  • 每种颜色通过一个 标签来规定。offset 属性用来定义渐变的开始和结束位置。

示例

<svg width="100%" height="800">
    <defs>
        <radialGradient id="grey_blue" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
            <stop offset="0%" style="stop-color:rgb(200,200,200);
stop-opacity:0" />
            <stop offset="50%" style="stop-color:rgb(255,0,0);
stop-opacity:0" />
            <stop offset="100%" style="stop-color:rgb(0,0,255);
stop-opacity:1" />
        </radialGradient>
    </defs>
    <ellipse cx="230" cy="200" rx="110" ry="100" style="fill:url(#grey_blue)" />

    <radialGradient id="grey_blue1" cx="20%" cy="40%" r="50%" fx="50%" fy="50%">
        <stop offset="0%" style="stop-color:rgb(200,200,200);
stop-opacity:0" />
        <stop offset="50%" style="stop-color:rgb(255,0,0);
stop-opacity:0" />
        <stop offset="100%" style="stop-color:rgb(0,0,255);
stop-opacity:1" />
    </radialGradient>
    </defs>
    <ellipse cx="230" cy="400" rx="110" ry="100" style="fill:url(#grey_blue1)" />
</svg>

渐变