前往
大廳
主題

SVG 自學微筆記(08) - 線性&放射漸層

冰抹茶拿鐵 | 2023-05-10 18:00:14 | 巴幣 0 | 人氣 204

不定更新、即將迎來結尾 (๑´ㅂ`๑)
學習資源: W3Schools、其他網路資料

漸層(Gradients)是W3Schools關於SVG基礎教學的最後部分,漸層的效果就是讓顏色漸漸地轉變成另一種顏色,而在SVG中的漸層又有兩種主要的類型,分別是線性(Linear)漸層和放射(Radial)漸層。

SVG : 漸層

  • 範例1 - 水平線性漸層
(左邊x2是100%,右邊x2是50%)
要達到水平漸層的效果,漸層的y1、y2位置必須相同,但是x1、x2位置必須不同,下面的漸層從左上最前端開始到右上最末端結束,當x2被修改成50%則代表漸層在中間就結束,後面都會是粉紅色,而不再有漸層效果。
<svg height="300" width="400">
    <defs>
        <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
            <stop offset="0%" style="stop-color: wheat;stop-opacity:1;"></stop>
            <stop offset="100%" style="stop-color: pink;stop-opacity:1;"></stop>
        </linearGradient>
    </defs>
    <ellipse cx="160" cy="100" rx="150" ry="80" fill="url(#grad1)"></ellipse>
</svg>
(ellipse的fill屬性可以透過url指定套用的顏色漸層效果)
  • 範例2 - 垂直線性漸層
(左邊y2是100%,右邊y2是50%)

要達到垂直漸層的效果,漸層的x1、x2位置必須相同,但是y1、y2位置必須不同,下面的漸層從左上最前端開始到左下最末端結束,當y2被修改成50%則代表漸層在中間就結束,後面都會是粉紅色,而不再有漸層效果。
<svg height="300" width="400">
    <defs>
        <linearGradient id="grad1" x1="0%" y1="0%" x2="0%" y2="100%">
            <stop offset="0%" style="stop-color: wheat;stop-opacity:1;"></stop>
            <stop offset="100%" style="stop-color: pink;stop-opacity:1;"></stop>
        </linearGradient>
    </defs>
    <ellipse cx="160" cy="100" rx="150" ry="80" fill="url(#grad1)"></ellipse>
</svg>
  • 範例3 - 傾斜線性漸層
要達到傾斜漸層的效果,漸層的x1、x2位置必須不同,而且y1、y2位置也必須不同,下面的漸層從左偏下的最前端開始到右偏上最末端結束。
<svg height="300" width="400">
    <defs>
        <linearGradient id="grad1" x1="0%" y1="80%" x2="100%" y2="10%">
            <stop offset="0%" style="stop-color: blue;stop-opacity:1;"></stop>
            <stop offset="100%" style="stop-color: red;stop-opacity:1;"></stop>
        </linearGradient>
    </defs>
    <ellipse cx="160" cy="100" rx="150" ry="80" fill="url(#grad1)"></ellipse>
    <text x="115" y="115" font-size="45" fill="white">SVG</text>
</svg>
  • 範例4 - 放射性漸層
由放射核心向外發散產生放射性漸層效果,簡單說就是圓形漸層。
<svg height="300" width="400">
    <defs>
        <radialGradient id="grad1" cx="50%" cy="50%" fx="50%" fy="50%" r="50%">
            <stop offset="0%" style="stop-color: blue;stop-opacity:1;"></stop>
            <stop offset="100%" style="stop-color: red;stop-opacity:1;"></stop>
        </radialGradient>
    </defs>
    <ellipse cx="160" cy="100" rx="150" ry="80" fill="url(#grad1)"></ellipse>
</svg>
(fx、fy設定成50%的效果跟沒有fx、fy的時候一模一樣)

透過調整fx、fy可以看到藍色核心區域向右下方移動的效果。
<svg height="300" width="400">
    <defs>
        <radialGradient id="grad1" cx="50%" cy="50%" fx="70%" fy="90%" r="50%">
            <stop offset="0%" style="stop-color: blue;stop-opacity:1;"></stop>
            <stop offset="100%" style="stop-color: red;stop-opacity:1;"></stop>
        </radialGradient>
    </defs>
    <ellipse cx="160" cy="100" rx="150" ry="80" fill="url(#grad1)"></ellipse>
</svg>

下次就是最後一篇微筆記要來補SVG Path的坑囉!  ヾ(*´∇`)ノ


參考資料
SVG Gradients (Linear) - W3Schools
SVG Gradients (Radial) - W3Schools

創作回應

更多創作