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 代碼:

<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> 元素用于添加文本