SVG 線性漸變
SVG 漸變必須在 <defs> 標簽中進行定義。
SVG 漸變
漸變是一種從一種顏色到另一種顏色的平滑過渡。另外,可以把多個顏色的過渡應用到同一個元素上。
在 SVG 中,有兩種主要的漸變類型:
- 線性漸變
- 放射性漸變
線性漸變
<linearGradient> 可用來定義 SVG 的線性漸變。
<linearGradient> 標簽必須嵌套在 <defs> 的內部。<defs> 標簽是 definitions 的縮寫,它可對諸如漸變之類的特殊元素進行定義。
線性漸變可被定義為水平、垂直或角形的漸變:
- 當 y1 和 y2 相等,而 x1 和 x2 不同時,可創(chuàng)建水平漸變
- 當 x1 和 x2 相等,而 y1 和 y2 不同時,可創(chuàng)建垂直漸變
- 當 x1 和 x2 不同,且 y1 和 y2 不同時,可創(chuàng)建角形漸變
請把下面的代碼拷貝到記事本,然后把文件保存為 "linear1.svg"。把此文件放入您的 web 目錄:
<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg"> <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)"/> </svg>
代碼解釋:
- <linearGradient> 標簽的 id 屬性可為漸變定義一個唯一的名稱
- fill:url(#orange_red) 屬性把 ellipse 元素鏈接到此漸變
- <linearGradient> 標簽的 x1、x2、y1、y2 屬性可定義漸變的開始和結束位置
- 漸變的顏色范圍可由兩種或多種顏色組成。每種顏色通過一個 <stop> 標簽來規(guī)定。offset 屬性用來定義漸變的開始和結束位置。
另一個例子:
<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg"> <defs> <linearGradient id="orange_red" 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="190" rx="85" ry="55" style="fill:url(#orange_red)"/> </svg>