Latest web development tutorials

SVG 漸變– 線性

SVG 漸變

漸變是一種從一種顏色到另一種顏色的平滑過渡。 另外,可以把多個顏色的過渡應用到同一個元素上。

SVG漸變主要有兩種類型:

  • Linear
  • Radial

SVG 線性漸變- <linearGradient>

<linearGradient>元素用於定義線性漸變。

<linearGradient>標籤必須嵌套在<defs>的內部。 <defs>標籤是definitions的縮寫,它可對諸如漸變之類的特殊元素進行定義。

線性漸變可以定義為水平,垂直或角漸變:

  • 當y1和y2相等,而x1和x2不同時,可創建水平漸變
  • 當x1和x2相等,而y1和y2不同時,可創建垂直漸變
  • 當x1和x2不同,且y1和y2不同時,可創建角形漸變

實例1

定義水平線性漸變從黃色到紅色的橢圓形:

下面是SVG代碼:

實例

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<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>

嘗試一下»

對於Opera用戶: 查看SVG文件 (右鍵單擊SVG圖形預覽源)。

代碼解析:

  • <linearGradient>標籤的id屬性可為漸變定義一個唯一的名稱
  • <linearGradient>標籤的X1,X2,Y1,Y2屬性定義漸變開始和結束位置
  • 漸變的顏色範圍可由兩種或多種顏色組成。 每種顏色通過一個<stop>標籤來規定。 offset屬性用來定義漸變的開始和結束位置。
  • 填充屬性把ellipse 元素鏈接到此漸變

實例2

定義一個垂直線性漸變從黃色到紅色的橢圓形:

下面是SVG代碼:

實例

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<defs>
<linearGradient id="grad1" 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="70" rx="85" ry="55" fill="url(#grad1)" />

</svg>

嘗試一下»

對於Opera用戶: 查看SVG文件 (右鍵單擊SVG圖形預覽源)。


實例3

定義一個橢圓形,水平線性漸變從黃色到紅色並添加一個橢圓內文本:

下面是SVG代碼:

實例

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<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)" />
<text fill="#ffffff" font-size="45" font-family="Verdana" x="150" y="86">
SVG</text>
</svg>

嘗試一下»

對於Opera用戶: 查看SVG文件 (右鍵單擊SVG圖形預覽源)。

代碼解析:

  • <text> 元素是用來添加一個文本