SVG 画像へ linearGradient 要素を使って線状のグラデーションをかける

インライン SVG 画像へグラデーションをかけるには、linearGradient 要素を使用します。linearGradient 要素を defs 要素で囲い定義化し、linearGradient 要素に付与した ID をグラデーションを適用したい画像要素の fill 属性へリンクします。

グラデーション自体は、stop 要素で作ります。stop 要素には offset 属性と stop-color 属性を指定します。offset 属性は左端を始点にどこの位置までグラデーションを適応するかを指定し、stop-color 属性で、始点からの変化する色を指定します。

例えば、offset=”100%” stop-color=”red” とした場合は始点から終点までが全て red の指定になるためベタ塗りの赤となります。グラデーションを描写するには、最低2つの stop 要素が必要になります。

以下のコードでは、始点がオレンジ、終点が赤のグラデーションができます。

<svg width="250" height="250">
    <defs>
    <linearGradient id="sample">
      <stop offset="0%"   stop-color="orange" />
      <stop offset="100%" stop-color="red" />
    </linearGradient>
    </defs>
    
    <circle cx="100" cy="100" r="90" fill="url(#sample)" />
</svg>

上記コードのブラウザでの表示
始点がオレンジ、終点が赤のグラデーション

stroke にグラデーションをかける

stroke の色指定を linearGradient の id にすれば、stroke 部分にもグラデーションを適用できます。

<svg width="600" height="200">
    <defs>
    <linearGradient id="sample">
      <stop offset="0%"   stop-color="orange" />
      <stop offset="100%" stop-color="red" />
    </linearGradient>
    </defs>
    <rect x="50" y="50" width="500" height="100" fill="none" stroke="url(#sample)" stroke-width="20" />
</svg>

上記コードのブラウザでの表示
stroke にグラデーションをかけた

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です