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> 元素是用來新增一個文字
Stephen
rea***ephenzhao@live.com
經過測試,範例 3 中新增的文字是從自身左下角(以給出的坐標資料為原點)開始的,文字大小的改變都沿著往右上角的射線,始終在第一象限。
新增文字跟繪製圖形的坐標方向是不一樣的,這個點得注意。
Stephen
rea***ephenzhao@live.com