現実的には、ほとんどの場合、手動でコーディングする代わりにAdobe Illustratorなどのツールを使用してSVGファイルを作成しますが、一部のSVG機能は、画像にさらにポップさを与えるために手動で簡単に実装できます。 線形グラデーションはそのような機能の1つです。

例を挙げて学びましょう。 これが私たちのベースクロスボーン画像です:

Base SVG image

そして、これがそのSVGマークアップです。 パスデータを…で変更することで簡略化しました:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
  <style>.bones{fill:#ccc ;} .eye{fill:#666;}</style>

  <path class="bones" d="..."/>

  <path class="bones" d="..."/>

  <g>
    <path class="eye" d="..."/>
    <path class="eye" d="..."/>
  </g>
</svg>

これがオレンジ色のグラデーションのバージョンです。

SVG linear gradient example 1

そして、これがマークアップです。 ハイライトされたセクションとdefs、linearGradient、stop要素に注目してください。

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
  <style>.eye{fill:#F9EC31;}</style>

  <defs>
    <linearGradient id="bones-gradient" x1="0%" y1="0%" x2="100%" y2="0%">
	  <stop offset="0%" style="stop-color:#FF9133;" />
	  <stop offset="100%" style="stop-color:#FF0015;" />
    </linearGradient>
  </defs>

  <g fill="url(#bones-gradient)">
	  <path class="bones" d="..."/>
	  <path class="bones" d="..."/>
  </g>

  <g>
    <path class="eye" d="..."/>
    <path class="eye" d="..."/>
  </g>
</svg>

現在、複数のカラーストップとstop-opacityを使用したバージョンです。 また、目の塗りつぶしの不透明度の使用にも注意してください。

SVG linear gradient example 2

そしてそのマークアップ:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
  <style>.eye{fill:#211533; fill-opacity: 0.5;}</style>

  <defs>
	<linearGradient id="bones-gradient" x1="0%" y1="0%" x2="100%" y2="0%">
	  <stop offset="0%" style="stop-color:#f8f8f8;stop-opacity:0.5" />
	  <stop offset="50%" style="stop-color:#fc00ff;stop-opacity:1" />
	  <stop offset="100%" style="stop-color:#f8f8f8;stop-opacity:0.5" />
	</linearGradient>
  </defs>

  <g fill="url(#bones-gradient)">
	  <path class="bones" d="..."/>
	
	  <path class="bones" d="..."/>
  </g>

  <g>
    <path class="eye" d="..."/>
    <path class="eye" d="..."/>
  </g>
</svg>

そして最後に、この最後の例では、グラデーションに異なる角度を使用します。

SVG linear gradient example 3

マークアップは次のとおりです。

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
  <style>.eye{fill:#F9EC31;}</style>

  <defs>
	<linearGradient id="bones-gradient" x1="0%" y1="0%" x2="50%" y2="100%">
	  <stop offset="0%" style="stop-color:blue;" />
	  <stop offset="100%" style="stop-color:#FF0015;" />
	</linearGradient>
  </defs>

  <g fill="url(#bones-gradient)">
	  <path class="bones" d="..."/>

	  <path class="bones" d="..."/>
  </g>

  <g>
    <path class="eye" d="...."/>
    <path class="eye" d="..."/>
  </g>
</svg>