Skip to content

SVG チートシート

解像度非依存の画像のための Scalable Vector Graphics。

01

基本の構造

SVG 文書の骨格

SVG の名前空間を宣言するのが、xmlns 属性です。ピクセルでの描画サイズを設定するのが、width/height で、内部の座標系を定義するのが、viewBox です。スタンドアロンの .svg ファイルでも、HTML にインラインで埋め込まれても良く、後者では、XML の宣言と xmlns が省略可能です。

svg
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg"
     width="200" height="200"
     viewBox="0 0 200 200">
  <!-- SVG content goes here -->
  <rect x="0" y="0" width="200" height="200" fill="#eee"/>
</svg>

HTML への SVG 埋め込み

最も柔軟なのが、インライン SVG です。HTML のように CSS でスタイルし、JS でスクリプトできます。静的な画像として SVG を扱うのが(内部の CSS/JS なし)、<img> と background-image です。独自の DOM を持つ別の文書としてロードし、いくつかのスクリプティングを可能にするのが、<object> です。

svg
<!-- 1. Inline (best for styling and scripting) -->
<svg width="100" height="100">
  <circle cx="50" cy="50" r="40" fill="red"/>
</svg>

<!-- 2. As an image (no CSS/JS interaction) -->
<img src="icon.svg" alt="Icon" width="100" height="100">

<!-- 3. As a background (limited styling) -->
<div style="background: url('icon.svg') no-repeat;"></div>

<!-- 4. Via object/embed (allows scripting) -->
<object data="icon.svg" type="image/svg+xml"></object>

座標系

左手系の座標系を使うのが、SVG です。原点が左上で、X が右へ、Y が下へです。内部の座標空間を定義するのが、viewBox 属性です。要素の width/height に合わせ、SVG がコンテンツを拡縮するため、200px の要素の中の 0 0 100 100 の viewBox が、すべてを 2 倍で描画します。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <!-- Origin (0,0) is top-left, like Canvas -->
  <!-- X increases rightward, Y increases downward -->

  <!-- A point at (50, 25) -->
  <circle cx="50" cy="25" r="3" fill="black"/>

  <!-- The viewBox stretches content to fill width/height -->
  <!-- viewBox="minX minY width height" -->
</svg>

<!-- viewBox 0 0 100 100 in a 200x200 element = 2x zoom -->
<svg width="200" height="200" viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="50" fill="blue"/>
</svg>

幅、高さ、単位

px と等価なのが、(接尾辞なしの)ユーザー単位です。親を基準とするのが、パーセンテージです。レスポンシブな SVG のためには、width/height を省き、viewBox を設定しましょう — アスペクト比を保ちつつ、SVG がコンテナへ拡縮します。割合を保つのが、viewBox 付きの高さの「auto」です。

svg
<svg width="200" height="100">
  <!-- Default unit is the user unit (px equivalent) -->
</svg>

<!-- Common units: px, em, %, pt, cm, mm, in -->
<svg width="50%" height="auto" viewBox="0 0 100 100">
  <!-- % is relative to the parent element -->
</svg>

<!-- No width/height + viewBox = fully responsive -->
<svg viewBox="0 0 100 100" style="width:100%;height:auto;">
  <!-- Scales to container, preserves aspect ratio -->
</svg>

名前空間と xlink

<use>、<image>、<a> 上での直接の href 対応を導入し、xlink:href を非推奨としたのが、SVG 2 です。素の href をサポートするのが、モダンなブラウザです。非常に古いブラウザをサポートする必要がある場合だけ、xlink の名前空間を保ちましょう。厳密に xmlns 属性を必要としないのが、HTML でのインライン SVG です。

svg
<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">

  <!-- Modern SVG 2: use href directly -->
  <use href="#icon"/>

  <!-- Legacy SVG 1.1: use xlink:href -->
  <use xlink:href="#icon"/>
</svg>

<!-- In HTML5 inline SVG, the xmlns is optional -->
<!-- But xlink namespace is needed if you use xlink:href -->

コメントとメタデータ

スクリーンリーダーが読むアクセシビリティのテキストを提供するのが、<title> と <desc> です。意味のある SVG には必ず含めましょう。ツールのための構造化データを(RDF、Dublin Core)保持するのが、<metadata> です。HTML と同じ <!-- --> の構文を使うのが、コメントです。

svg
<svg width="100" height="100" viewBox="0 0 100 100">
  <!-- This is an XML comment (same as HTML) -->

  <!-- Metadata is hidden from rendering -->
  <metadata>
    <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
      <dc:title xmlns:dc="http://purl.org/dc/elements/1.1/">My Icon</dc:title>
    </rdf:RDF>
  </metadata>

  <!-- title and desc for accessibility -->
  <title>Shopping Cart Icon</title>
  <desc>A red shopping cart with 3 items</desc>

  <circle cx="50" cy="50" r="40" fill="red"/>
</svg>
02

形状

長方形(rect)

x、y、width、height を要求するのが、rect です。角丸を作るのが、rx/ry です(rx だけが設定された場合、ry が rx をデフォルトとします)。内部を透明にするのが、fill='none' です。縁を中心とするのが、stroke-width なので、半分が幾何の外側へ広がります。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <!-- Basic rectangle -->
  <rect x="10" y="10" width="80" height="50" fill="steelblue"/>

  <!-- Rounded corners -->
  <rect x="110" y="10" width="80" height="50"
        rx="10" ry="10" fill="tomato"/>

  <!-- Stroked, no fill -->
  <rect x="10" y="70" width="80" height="20"
        fill="none" stroke="black" stroke-width="2"/>
</svg>

円と楕円

中心(cx、cy)と半径 r により定義されるのが、circle です。引き伸ばしのための別々の rx と ry を持つのが、ellipse です。省略された場合、0 を cx/cy のデフォルトとするのが、両方です。角丸を持てないのが(既に曲がっているため)、rect と違い、円/楕円です。

svg
<svg width="200" height="120" viewBox="0 0 200 120">
  <!-- circle: cx, cy (center), r (radius) -->
  <circle cx="50" cy="60" r="40" fill="gold"/>

  <!-- ellipse: cx, cy, rx (x radius), ry (y radius) -->
  <ellipse cx="150" cy="60" rx="50" ry="30" fill="mediumpurple"/>

  <!-- Circle as an ellipse (rx == ry) -->
  <ellipse cx="100" cy="20" rx="15" ry="15" fill="black"/>
</svg>

線

2 つの点を結ぶのが、line です。塗りを持たず(stroke のみ)、破線を作るのが、stroke-dasharray です。反復されるのが、「dash-length,gap-length」のパターンです。端のキャップを制御するのが、stroke-linecap(butt、round、square)です。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <!-- line: x1,y1 (start) to x2,y2 (end) -->
  <line x1="10" y1="10" x2="190" y2="10" stroke="black" stroke-width="2"/>

  <!-- Diagonal line -->
  <line x1="10" y1="90" x2="190" y2="10" stroke="red" stroke-width="3"/>

  <!-- Dashed line -->
  <line x1="10" y1="50" x2="190" y2="50"
        stroke="blue" stroke-width="2" stroke-dasharray="10,5"/>
</svg>

Polyline と Polygon

形状を閉じずに、接続された線分を描くのが、polyline です(閉じたものとして塗りが適用されますが、端を結ぶ stroke はありません)。最後の点を最初へ戻し結ぶことで、自動的に閉じるのが、polygon です。x,y のペアの、スペースかカンマ区切りのリストが、points です。

svg
<svg width="200" height="120" viewBox="0 0 200 120">
  <!-- polyline: open shape (no auto-close) -->
  <polyline points="10,10 50,90 100,10 150,90 190,10"
            fill="none" stroke="green" stroke-width="2"/>

  <!-- polygon: closed shape (auto-connects last to first) -->
  <polygon points="100,10 190,110 10,110"
           fill="lime" stroke="black" stroke-width="1"/>

  <!-- Star (polygon with 10 points) -->
  <polygon points="50,5 61,38 95,38 67,58 78,90 50,70 22,90 33,58 5,38 39,38"
           fill="gold" stroke="orange"/>
</svg>

よくある形状の属性

2 つの主要なペイントのプロパティが、fill と stroke です。要素全体に影響するのが、opacity で、独立に作用するのが、fill-opacity と stroke-opacity です。線の端を形作るのが、stroke-linecap(butt/round/square)で、角を形作るのが、stroke-linejoin(miter/round/bevel)です。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <rect x="10" y="10" width="80" height="80"
        fill="#3498db"
        fill-opacity="0.5"
        stroke="#2c3e50"
        stroke-width="3"
        stroke-opacity="0.8"
        stroke-dasharray="5,3"
        stroke-linecap="round"
        stroke-linejoin="round"
        opacity="0.9"/>

  <!-- opacity affects the whole element -->
  <!-- fill-opacity/stroke-opacity affect parts independently -->
</svg>

塗りのルール(evenodd)

形状の重なる領域がどう満たされるかを決めるのが、fill-rule です。巻きの方向に基づき満たすのが、「nonzero」(デフォルト)です。奇数回囲まれた領域を満たすのが、「evenodd」で — 自己交差するパスや同心の多角形のために、クラシックな「ドーナツの穴」効果を作るのが、これです。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <!-- Default fill-rule: nonzero -->
  <polygon points="50,10 90,90 10,90 50,30 80,80 20,80"
           fill="red" fill-rule="nonzero"/>

  <!-- fill-rule: evenodd creates holes in overlapping shapes -->
  <polygon points="150,10 190,90 110,90 150,30 180,80 120,80"
           fill="blue" fill-rule="evenodd"/>
</svg>
03

Path

パスコマンドの概観

最も強力な SVG の形状であるのが、<path> 要素です。描画コマンドの文字列を保持するのが、d 属性です。絶対座標を使うのが、大文字のコマンドで、現在のペンの位置に対する相対座標を使うのが、小文字です。コアのコマンドが、M、L、C、Q、A、Z です。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <!-- The d attribute contains all path commands -->
  <path d="M 10 10 L 190 10 L 100 90 Z" fill="none" stroke="black"/>

  <!-- Uppercase = absolute, lowercase = relative -->
  <!-- M = moveto (lift pen, move) -->
  <!-- L = lineto (draw straight line) -->
  <!-- H = horizontal lineto, V = vertical lineto -->
  <!-- C = cubic bezier, S = smooth cubic -->
  <!-- Q = quadratic bezier, T = smooth quadratic -->
  <!-- A = arc, Z = closepath -->
</svg>

M、L、H、V、Z(線)

描画せずペンを動かすのが、M です。点へ描くのが、L で、水平/垂直線を描くのが(1 座標)、H/V、パスを開始へ戻して閉じるのが、Z です。現在の位置からのオフセットとして座標を解釈するのが、(l、h、v、z の)小文字版で、サブパスの再利用が可能になります。

svg
<svg width="200" height="120" viewBox="0 0 200 120">
  <!-- M = moveto, L = lineto, Z = close path -->
  <path d="M 10 10 L 190 10 L 190 110 L 10 110 Z"
        fill="none" stroke="black"/>

  <!-- H = horizontal line, V = vertical line (one coord each) -->
  <path d="M 10 60 H 190" stroke="red"/>

  <!-- Relative commands (lowercase): coords are offsets -->
  <path d="M 10 80 l 30 -20 l 30 20 l 30 -20 l 30 20"
        fill="none" stroke="blue"/>

  <!-- Multiple M's create subpaths (disconnected segments) -->
  <path d="M 10 100 L 50 100 M 100 100 L 150 100" stroke="green"/>
</svg>

C と S(三次ベジェ)

曲線を引く 2 つの制御点付きで、三次ベジェを描くのが、C です。開始の接線に影響するのが、最初の制御点(x1,y1)で、終了の接線に影響するのが、2 番目(x2,y2)です。前の曲線の 2 番目の制御点を映し返すことで、滑らかに続けるのが、S です — 新しい 2 番目の制御点と終点だけを指定します。

svg
<svg width="240" height="120" viewBox="0 0 240 120">
  <!-- C = cubic bezier: two control points + endpoint -->
  <!-- C x1 y1, x2 y2, x y -->
  <path d="M 10 60 C 60 10, 180 110, 230 60"
        fill="none" stroke="red" stroke-width="2"/>

  <!-- S = smooth cubic: control point mirrors the previous -->
  <!-- S x2 y2, x y (first control point is auto-mirrored) -->
  <path d="M 10 100 C 60 50, 100 50, 120 100 S 200 150, 230 100"
        fill="none" stroke="blue" stroke-width="2"/>

  <!-- Multiple cubics in one path -->
  <path d="M 10 20 C 40 0, 70 40, 100 20 C 130 0, 160 40, 190 20"
        fill="none" stroke="green"/>
</svg>

Q と T(二次ベジェ)

2 つでなく 1 つの制御点を使うのが、Q です。C より単純だが柔軟性が低いです。制御点を映し返すことで Q を滑らかに続け、終点だけを必要とするのが、T です。フォントのグリフと、単一の制御点で十分な単純なアイコンのパスでよくあるのが、二次曲線です。

svg
<svg width="200" height="120" viewBox="0 0 200 120">
  <!-- Q = quadratic bezier: one control point + endpoint -->
  <!-- Q x1 y1, x y -->
  <path d="M 10 100 Q 100 0, 190 100"
        fill="none" stroke="purple" stroke-width="2"/>

  <!-- T = smooth quadratic: control point auto-mirrored -->
  <path d="M 10 60 Q 50 20, 90 60 T 170 60"
        fill="none" stroke="orange" stroke-width="2"/>

  <!-- Q is simpler than C but less precise — good for curves -->
  <!-- with a single bend, like basic arcs and waves -->
</svg>

A(弧)

楕円の弧を描くのが、A です。半径が、rx、ry で、楕円を傾けるのが、x-rotation です。点の間のより短いかより長い弧を選ぶのが、large-arc-flag(0/1)で、反時計回りか時計回りを選ぶのが、sweep-flag(0/1)です。厄介なのが、弧であり — 予測可能性のために、多くのデザイナーが代わりに C の曲線を使います。

svg
<svg width="200" height="150" viewBox="0 0 200 150">
  <!-- A rx ry, x-rotation, large-arc-flag, sweep-flag, x y -->
  <path d="M 10 75 A 60 60, 0, 0, 1, 130 75"
        fill="none" stroke="red" stroke-width="2"/>

  <!-- large-arc-flag: 0 = small arc, 1 = large arc -->
  <!-- sweep-flag: 0 = counterclockwise, 1 = clockwise -->

  <!-- Large arc (the long way around) -->
  <path d="M 10 75 A 60 60, 0, 1, 1, 130 75"
        fill="none" stroke="blue" stroke-width="2"/>

  <!-- Elliptical arc (rx != ry) -->
  <path d="M 10 120 A 80 30, 0, 0, 0, 170 120"
        fill="none" stroke="green" stroke-width="2"/>
</svg>

実用的なパスの例

形状をたどるため、M、L、C、Z を組み合わせるのが、実世界のアイコンです。滑らかな曲線のために、三次ベジェを使うのが、ハートで、丸い線のキャップ付きの 3 点だけであるのが、チェックマークです。長方形のための H/V の線と、尾のための L コマンドを混ぜるのが、吹き出しです。単純に始め、その後、制御点を洗練させましょう。

svg
<svg width="200" height="120" viewBox="0 0 200 120">
  <!-- Heart shape -->
  <path d="M 100 30
           C 70 0, 20 20, 20 60
           C 20 90, 60 110, 100 120
           C 140 110, 180 90, 180 60
           C 180 20, 130 0, 100 30 Z"
        fill="red"/>

  <!-- Checkmark -->
  <path d="M 20 60 L 50 90 L 100 20"
        fill="none" stroke="green" stroke-width="6"
        stroke-linecap="round" stroke-linejoin="round"/>

  <!-- Speech bubble (combines lines and curves) -->
  <path d="M 20 20 H 180 V 80 H 60 L 40 100 L 45 80 H 20 Z"
        fill="lightblue" stroke="navy"/>
</svg>
04

テキスト

基本のテキスト

デフォルトで上部でなく、テキストのベースラインを参照するのが、y の座標です。x に対する水平の整列を制御するのが、text-anchor(start/middle/end)で、垂直の整列を制御するのが、dominant-baseline(auto/middle/hanging/...)です。テキストの中央寄せには、どちらも不可欠です。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <text x="10" y="50" font-family="Arial" font-size="24"
        fill="black">Hello SVG!</text>

  <!-- x, y sets the baseline position (y is the text baseline) -->
  <!-- Use dominant-baseline to change the vertical anchor -->
  <text x="100" y="50" font-size="20" fill="blue"
        text-anchor="middle" dominant-baseline="middle">Centered</text>
</svg>

テキストのスタイリング

属性として、ほとんどの CSS のフォントプロパティを SVG のテキストがサポートします。標準のフォントスタックを受け付けるのが、font-family です。テキスト上の stroke が輪郭を描くため、塗りを不明瞭にしないよう、小さい stroke-width を使いましょう。CSS のように機能するのが、letter-spacing と word-spacing です。

svg
<svg width="300" height="120" viewBox="0 0 300 120">
  <text x="10" y="30"
        font-family="Georgia, serif"
        font-size="28"
        font-weight="bold"
        font-style="italic"
        fill="darkblue"
        stroke="navy"
        stroke-width="0.5"
        text-decoration="underline"
        letter-spacing="2">Styled Text</text>

  <!-- font-family uses CSS font stacks -->
  <!-- font-weight: normal, bold, 100-900 -->
  <!-- font-style: normal, italic, oblique -->
</svg>

tspan(サブテキスト)

テキストの一部を異なるようにスタイル・配置させてくれるのが(HTML の <span> のように)、<tspan> です。前の文字に対する相対のオフセットが、dx/dy で、新しい位置への跳躍が、絶対の x/y です(改行のためには、元の値付きの x と、dy を使います)。SVG での複数行テキストを構築する方法が、tspan です。

svg
<svg width="300" height="100" viewBox="0 0 300 100">
  <text x="10" y="50" font-size="20" fill="black">
    <tspan font-weight="bold" fill="red">Bold red</tspan>
    <tspan dx="10" font-style="italic">italic</tspan>
    <tspan x="10" dy="30">New line via dy</tspan>
    <tspan dx="10" font-size="14">smaller</tspan>
  </text>

  <!-- dx/dy: relative offset from previous position -->
  <!-- x/y: absolute position (useful for line breaks) -->
</svg>

パス上のテキスト

任意の path 要素に沿ってテキストを描画するのが、<textPath> です。パスを参照するのが、(モダンな)href か、(レガシーの)xlink:href による id 経由です。パスに沿ってテキストを配置するのが、(長さかパーセンテージの)startOffset です。弧、円、カスタム形状上の湾曲したラベルのための、標準の技法が、これです。

svg
<svg width="300" height="150" viewBox="0 0 300 150">
  <!-- Define a path (can be invisible) -->
  <defs>
    <path id="curve" d="M 20 100 Q 150 0, 280 100" fill="none"/>
  </defs>

  <!-- Text follows the path via xlink:href / href -->
  <text font-size="20" fill="purple">
    <textPath href="#curve">Text along a curved path!</textPath>
  </text>

  <!-- startOffset shifts where the text begins on the path -->
  <text font-size="14" fill="gray">
    <textPath href="#curve" startOffset="50%" text-anchor="middle">
      Centered on path
    </textPath>
  </text>
</svg>

書字モードと direction

テキストを上から下へ流させるのが(東アジアのタイポグラフィで一般的)、writing-mode='tb' です。右から左の文字体系のために、文字の順序を逆にするのが、direction='rtl' です。任意の回転のためには、transform 属性を使い — (cx, cy) の点の周りで回転させるのが、rotate(angle, cx, cy) です。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <!-- Vertical text (top-to-bottom) -->
  <text x="50" y="20" writing-mode="tb" font-size="20">Vertical</text>

  <!-- Right-to-left text -->
  <text x="190" y="100" direction="rtl" font-size="20"
        text-anchor="end">RTL text</text>

  <!-- Rotated text (via transform) -->
  <text x="100" y="100" font-size="20"
        transform="rotate(45, 100, 100)">Rotated 45°</text>
</svg>

テキストのアクセシビリティ

デフォルトで選択可能でアクセシブルであるのが、SVG のテキストですが、装飾的な SVG には、<title> と <desc> があるべきです。UI 要素として使われるインライン SVG のためには、スクリーンリーダーが意味を告知するよう、role='img' と aria-label を加えましょう。重要な情報を SVG のテキストにだけ置くことは避け、よりアクセシブルなのが、HTML のテキストです。

svg
<svg width="200" height="80" viewBox="0 0 200 80">
  <title>Error Icon</title>
  <desc>A red circle with a white exclamation mark</desc>

  <!-- role and aria-label for screen readers -->
  <text role="img" aria-label="Error: 3 items need attention"
        x="100" y="45" text-anchor="middle"
        font-size="24" fill="red">! Error</text>
</svg>
05

グラデーション

リニアグラデーション

線に沿って色を遷移させるのが、linearGradient です。方向を定義するのが、x1/y1 から x2/y2 で(左から右が、0% 0% から 100% 0%)、色の点を定義するのが、<stop> の要素で、0〜100% か 0〜1 が、offset です。参照するのが、fill='url(#id)' によるグラデーションです。<defs> 内にグラデーションがなければなりません。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <defs>
    <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
      <stop offset="0%" stop-color="red"/>
      <stop offset="50%" stop-color="yellow"/>
      <stop offset="100%" stop-color="green"/>
    </linearGradient>
  </defs>

  <rect x="10" y="10" width="180" height="80" fill="url(#grad1)"/>
</svg>

ラジアルグラデーション

中心点から放射するのが、radialGradient です。中心が、cx/cy で、半径が、r です。焦点が、fx/fy で(0% の色が始まる場所)— それをオフセットすると、方向性のある光の効果が作れます。デフォルト:cx/cy が 50%、r が 50%、cx/cy を映し返すのが、fx/fy です。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <defs>
    <radialGradient id="grad2" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
      <stop offset="0%" stop-color="white"/>
      <stop offset="50%" stop-color="orange"/>
      <stop offset="100%" stop-color="darkred"/>
    </radialGradient>
  </defs>

  <circle cx="100" cy="100" r="90" fill="url(#grad2)"/>
</svg>

グラデーションの単位と広がり

座標が、各形状に(0〜1)相対になるのが(デフォルトの)、gradientUnits='objectBoundingBox' です。そのため、同じグラデーションが、任意の要素に合います。絶対の SVG 座標を使うのが、userSpaceOnUse です。そのため、グラデーションが文書内に配置され、複数の形状をまたぐグラデーションの整列に有用です。

svg
<svg width="300" height="100" viewBox="0 0 300 100">
  <defs>
    <!-- objectBoundingBox (default): coords are 0-1 relative to the shape -->
    <linearGradient id="g1" x1="0" y1="0" x2="1" y2="0">
      <stop offset="0" stop-color="blue"/>
      <stop offset="1" stop-color="cyan"/>
    </linearGradient>

    <!-- userSpaceOnUse: coords are in the SVG's user units -->
    <linearGradient id="g2" x1="0" y1="0" x2="200" y2="0"
                    gradientUnits="userSpaceOnUse">
      <stop offset="0" stop-color="red"/>
      <stop offset="1" stop-color="yellow"/>
    </linearGradient>

    <!-- spreadMethod: pad (default), reflect, repeat -->
    <linearGradient id="g3" x1="0" y1="0" x2="0.3" y2="0"
                    spreadMethod="repeat">
      <stop offset="0" stop-color="green"/>
      <stop offset="1" stop-color="lime"/>
    </linearGradient>
  </defs>
  <rect width="100" height="100" x="0" fill="url(#g1)"/>
  <rect width="100" height="100" x="100" fill="url(#g2)"/>
  <rect width="100" height="100" x="200" fill="url(#g3)"/>
</svg>

ストップの不透明度と複数のストップ

透明度の遷移のための、stop-opacity(0〜1)を、各ストップが持てます。複雑なカラーランプのためには、多くのストップを組み合わせましょう。透明な青から上部が、不透明な暗い赤へ下部が、フェードするのが、この夕日のグラデーションです — 大気の背景のための、よくある技法です。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <defs>
    <linearGradient id="sunset" x1="0" y1="0" x2="0" y2="1">
      <stop offset="0%" stop-color="deepskyblue" stop-opacity="0"/>
      <stop offset="40%" stop-color="orange" stop-opacity="0.8"/>
      <stop offset="70%" stop-color="orangered"/>
      <stop offset="100%" stop-color="darkred"/>
    </linearGradient>
  </defs>
  <rect width="200" height="200" fill="url(#sunset)"/>
</svg>

グラデーションの再利用

<defs> 内でグラデーションを一度定義し、fill='url(#id)' 経由で、任意の数の形状上で参照しましょう。既存のものから新しいグラデーションを派生させ、(方向のような)一部の属性だけを上書きするのが、href です。これで、SVG が DRY に保たれ、ファイルサイズが減ります。

svg
<svg width="300" height="100" viewBox="0 0 300 100">
  <defs>
    <!-- A reusable gradient -->
    <linearGradient id="metal" x1="0" y1="0" x2="0" y2="1">
      <stop offset="0%" stop-color="#eee"/>
      <stop offset="50%" stop-color="#999"/>
      <stop offset="100%" stop-color="#333"/>
    </linearGradient>

    <!-- Gradient referencing another via href -->
    <linearGradient id="metal-horizontal" href="#metal"
                    x1="0" y1="0" x2="1" y2="0"/>
  </defs>

  <!-- Same gradient on multiple shapes -->
  <rect x="10" y="10" width="80" height="80" fill="url(#metal)"/>
  <circle cx="150" cy="50" r="40" fill="url(#metal)"/>
  <rect x="210" y="10" width="80" height="80" fill="url(#metal-horizontal)"/>
</svg>
06

パターン

基本のパターン

繰り返しのグラフィックをタイル化するのが、<pattern> です。1 つのタイルを定義するのが、パターンの子で、タイルサイズを設定するのが、width/height です。タイルの寸法が、満たされる形状に依存しない SVG のユーザー単位にあることを意味するのが(推奨される)、patternUnits='userSpaceOnUse' です。参照するのが、fill='url(#id)' です。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <defs>
    <pattern id="dots" x="0" y="0" width="20" height="20"
             patternUnits="userSpaceOnUse">
      <circle cx="10" cy="10" r="3" fill="steelblue"/>
    </pattern>
  </defs>

  <rect width="200" height="200" fill="url(#dots)"/>
</svg>

パターンの単位

タイルを形状の分数としてサイズ化するのが(デフォルトの)、patternUnits='objectBoundingBox' です。パターンが各形状と共に拡縮します。絶対単位を使い、パターンがサイズにかかわらず、形状をまたいで一貫するのが、「userSpaceOnUse」です。userSpaceOnUse を使うのが、ほとんどの実世界のパターンです。

svg
<svg width="300" height="100" viewBox="0 0 300 100">
  <defs>
    <!-- objectBoundingBox (default): tile size is relative to shape -->
    <!-- 0.1 = 10% of the shape's width/height -->
    <pattern id="p1" width="0.1" height="0.1">
      <rect width="10" height="10" fill="red" opacity="0.5"/>
    </pattern>

    <!-- userSpaceOnUse: tile size is in SVG units -->
    <pattern id="p2" width="20" height="20"
             patternUnits="userSpaceOnUse">
      <rect width="10" height="10" fill="blue" opacity="0.5"/>
    </pattern>
  </defs>

  <rect width="150" height="100" fill="url(#p1)"/>
  <rect x="150" width="150" height="100" fill="url(#p2)"/>
</svg>

縞模様とチェッカーボード

パターン全体を回転・拡縮・傾斜させるのが、patternTransform です。縞模様のためには、タイルの半分を 1 色で、もう半分を別の色で満たし、その後回転させましょう。タイルごとに 4 つの rect(か 2 つの L 字型のペア)を使うのが、チェッカーボードです。図式とテクスチャでよくあるのが、これらのパターンです。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <defs>
    <!-- Diagonal stripes -->
    <pattern id="stripes" width="20" height="20"
             patternUnits="userSpaceOnUse"
             patternTransform="rotate(45)">
      <rect width="20" height="10" fill="gold"/>
      <rect y="10" width="20" height="10" fill="black"/>
    </pattern>

    <!-- Checkerboard -->
    <pattern id="checker" width="40" height="40"
             patternUnits="userSpaceOnUse">
      <rect width="40" height="40" fill="white"/>
      <rect width="20" height="20" fill="black"/>
      <rect x="20" y="20" width="20" height="20" fill="black"/>
    </pattern>
  </defs>

  <rect width="100" height="200" fill="url(#stripes)"/>
  <rect x="100" width="100" height="200" fill="url(#checker)"/>
</svg>

パターンのコンテンツの単位

(タイルサイズでなく)パターンの子要素のための座標系を制御するのが、patternContentUnits です。子の座標が形状の分数になるのが、「objectBoundingBox」です。パターンの詳細が、各形状と共に比例的に拡縮してほしいときに有用です。まれですが強力です。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <defs>
    <!-- patternContentUnits: how the pattern's children are measured -->
    <!-- userSpaceOnUse (default): children use SVG units -->
    <!-- objectBoundingBox: children are relative to the shape -->
    <pattern id="pb" width="0.25" height="0.25"
             patternContentUnits="objectBoundingBox">
      <circle cx="0.125" cy="0.125" r="0.05" fill="green"/>
    </pattern>
  </defs>

  <!-- The dots scale with each shape's bounding box -->
  <rect width="100" height="100" fill="url(#pb)"/>
  <rect x="100" width="100" height="200" fill="url(#pb)"/>
</svg>

ネストしたパターン

グラデーション、他のパターン、任意の SVG のコンテンツを、パターンが含められます。各セルを、控えめなグラデーションで満たし、上にグリッドの線を描くのが、このグリッドのパターンです。複雑なテクスチャを構築させてくれるのが、ネストです。非常に小さいタイルでのパフォーマンス問題を避けるため、タイルサイズは妥当に保ちましょう。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <defs>
    <!-- A pattern can reference another pattern or gradient -->
    <pattern id="grid" width="40" height="40"
             patternUnits="userSpaceOnUse">
      <rect width="40" height="40" fill="url(#cellGrad)"/>
      <path d="M 40 0 L 0 0 0 40" fill="none" stroke="#ccc"/>
    </pattern>

    <linearGradient id="cellGrad">
      <stop offset="0" stop-color="#f0f8ff"/>
      <stop offset="1" stop-color="#e0e0ff"/>
    </linearGradient>
  </defs>

  <rect width="200" height="200" fill="url(#grid)"/>
</svg>
07

Transform

Translate

tx, ty により要素を動かすのが、translate(tx, ty) です。ty が省略されると 0 をデフォルトとします。要素の座標系に適用されるのが、transform であるため、変換された原点に相対的であるのが、x/y の属性です。インライン SVG 上でモダンなブラウザで機能し、CSS トランジションでアニメーション化できるのが、(スタイル経由の)CSS の transform です。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <!-- Original -->
  <rect x="10" y="10" width="40" height="40" fill="red"/>

  <!-- Translated 80px right -->
  <rect x="10" y="10" width="40" height="40" fill="blue"
        transform="translate(80, 0)"/>

  <!-- translate with one arg moves only horizontally -->
  <rect x="10" y="10" width="40" height="40" fill="green"
        transform="translate(0, 50)"/>

  <!-- Equivalent in CSS (for inline SVG in HTML) -->
  <rect x="10" y="10" width="40" height="40" fill="orange"
        style="transform: translate(150px, 0);"/>
</svg>

回転

(cx, cy) の点の周りで角度度回転させるのが、rotate(angle, cx, cy) です。cx/cy なしでは、原点(0,0)の周りで回転します。これはしばしば望むものではありません。時計回り(正)か反時計回り(負)であるのが、角度です。要素をその場で回転させるには、必ず中心を指定しましょう。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <rect x="50" y="50" width="100" height="20" fill="red"/>

  <!-- rotate(angle) around origin (0,0) -->
  <rect x="50" y="50" width="100" height="20" fill="blue"
        transform="rotate(45)"/>

  <!-- rotate(angle, cx, cy) around point (cx, cy) -->
  <rect x="50" y="50" width="100" height="20" fill="green"
        transform="rotate(45, 100, 60)"/>

  <!-- Negative angles rotate counterclockwise -->
  <rect x="50" y="50" width="100" height="20" fill="orange"
        transform="rotate(-30, 100, 60)"/>
</svg>

スケールとスキュー

寸法を掛けるのが、scale(sx, sy) です。1 引数が両方を等しく拡縮します。stroke-width と位置にも影響するのが、スケーリングです。軸に沿って角度により要素をせん断するのが、skewX/skewY です。原点(0,0)に相対的であるのが、すべての transform であるため、x=100 の形状の拡縮も、それを動かします。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <!-- Original square -->
  <rect x="10" y="10" width="50" height="50" fill="red"/>

  <!-- scale(2): 2x in both dimensions -->
  <rect x="10" y="10" width="50" height="50" fill="blue"
        transform="scale(2)"/>

  <!-- scale(sx, sy): different x and y scaling -->
  <rect x="10" y="10" width="50" height="50" fill="green"
        transform="scale(1, 2)"/>

  <!-- skewX / skewY: shear the shape -->
  <rect x="10" y="10" width="50" height="50" fill="orange"
        transform="skewX(30)"/>
</svg>

Matrix の transform

すべての transform の基礎の形式であるのが、matrix(a,b,c,d,e,f) です。拡縮が、a,d で、スキューが、b,c、平行移動が、e,f です。読みやすさのために名前付きの transform(translate、rotate など)を使うのが、ほとんどの開発者ですが、道具が出力するのが matrix であり、transform の組み合わせやパースに有用です。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <!-- transform="matrix(a, b, c, d, e, f)" -->
  <!-- Represents: [a c e] [b d f] [0 0 1] -->
  <!-- New x = a*x + c*y + e -->
  <!-- New y = b*x + d*y + f -->

  <!-- Identity (no change) -->
  <rect width="50" height="50" fill="red" transform="matrix(1,0,0,1,0,0)"/>

  <!-- Translate (100, 50) -->
  <rect width="50" height="50" fill="blue" transform="matrix(1,0,0,1,100,50)"/>

  <!-- Scale 2x and translate -->
  <rect width="50" height="50" fill="green" transform="matrix(2,0,0,2,50,0)"/>
</svg>

transform の組み合わせ

右から左へ適用されるのが(最も右のものが最初に起きます)、属性内の複数の transform です。これは、まず自身の原点の周りで形状を回転させ、その後動かすのが、「translate(100,100) rotate(45)」という意味で — しばしば望むものです。インライン SVG のためには、transform-origin 付きの CSS の transform が、しばしばより直観的です。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <!-- Multiple transforms apply right-to-left -->
  <rect x="0" y="0" width="40" height="40" fill="red"
        transform="translate(100, 100) rotate(45) scale(2)"/>

  <!-- This means: scale, then rotate, then translate -->
  <!-- Order matters! rotate then translate != translate then rotate -->

  <!-- transform-origin via CSS (for inline SVG) -->
  <rect x="80" y="80" width="40" height="40" fill="blue"
        style="transform: rotate(45deg); transform-origin: center;"/>

  <!-- transform-origin: center, 50% 50%, or explicit coords -->
</svg>

transform-origin(CSS)

CSS で SVG をアニメーション化するときは、transform-origin を(SVG のユーザー単位で)明示的に設定し、transform-box(要素のバウンディングボックスには fill-box、SVG のキャンバスには view-box)を設定しましょう。なければ、要素ではなく、SVG の原点を中心に回転します。インライン SVG 上で機能するのが、CSS のアニメーションとトランジションです。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <style>
    .gear {
      transform-origin: 100px 100px;  /* SVG user units */
      transform-box: fill-box;        /* or view-box */
      animation: spin 4s linear infinite;
    }
    @keyframes spin {
      to { transform: rotate(360deg); }
    }
  </style>

  <circle class="gear" cx="100" cy="100" r="50" fill="orange"/>
  <circle cx="100" cy="100" r="10" fill="black"/>
</svg>
08

グループ(g)

基本のグループ化

要素を(fill、stroke、transform などの)属性を共有させ、単位として操作できるようグループ化するのが、<g> です。グループからプレゼンテーション属性を継承するのが、子です。複雑な SVG の整理と、複数の形状へ一度に transform を適用するのに、グループが不可欠です。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <g fill="steelblue" stroke="navy" stroke-width="2">
    <!-- Children inherit the group's attributes -->
    <circle cx="60" cy="60" r="30"/>
    <rect x="100" y="30" width="60" height="60" rx="5"/>
    <path d="M 30 150 L 100 110 L 170 150 Z"/>
  </g>

  <!-- Without g, you'd repeat fill/stroke on each element -->
</svg>

グループの transform

子のための新しい座標系を作るのが、<g> 上の transform です。再利用可能なコンポーネントを構築する鍵が、これです:(0,0) の周りで設計し、その後、translate でグループ全体を配置します。グループの変換された原点に相対的であるのが、子の座標です。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <!-- A transform on a group applies to all children -->
  <g transform="translate(100, 100) rotate(45)">
    <rect x="-30" y="-30" width="60" height="60" fill="red"/>
    <circle cx="0" cy="0" r="15" fill="white"/>
  </g>

  <!-- The group defines its own coordinate system -->
  <!-- Children use coords relative to the group's origin -->
  <g transform="translate(50, 150)">
    <text x="0" y="0">Origin here</text>
    <circle cx="0" cy="-20" r="5"/>
  </g>
</svg>

ネストしたグループ

任意に深くネストできるのが、グループです。複合するのが、各ネストした transform であり、順に、すべての祖先の transform の影響を受けるのが、最も内側の要素です。階層的なシーンを構築する方法が、これです(回転する手足を持つキャラクタ、動く手を持つ各手足など)。パフォーマンスのため、ネストは妥当に保ちましょう。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <g transform="translate(100, 100)">  <!-- outer group -->
    <g transform="scale(0.5)">          <!-- inner group -->
      <circle r="80" fill="blue"/>
      <g transform="translate(40, 0)">  <!-- innermost -->
        <circle r="20" fill="white"/>
      </g>
    </g>
  </g>

  <!-- Transforms compound: the innermost circle is -->
  <!-- translated, scaled, and translated again -->
</svg>

グループの ID と参照

グループに id を与え、<use href='#id'> で参照すれば、複製できます。SVG のスプライトと再利用可能なコンポーネントの基礎が、これです。<defs> 内に(直接描画されず)グループが住め、異なる transform 付きで何度もインスタンス化されます。<use> 上の属性の上書きには、限界があります。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <defs>
    <g id="star">
      <polygon points="50,5 61,38 95,38 67,58 78,90 50,70 22,90 33,58 5,38 39,38"
               fill="gold" stroke="orange"/>
    </g>
  </defs>

  <!-- Reference the group with <use> -->
  <use href="#star" transform="translate(0, 0) scale(0.5)"/>
  <use href="#star" transform="translate(100, 0) scale(0.5)"/>
  <use href="#star" transform="translate(0, 50) scale(0.3)"/>
</svg>

条件付きグループ

CSS(hover、active の状態)と JavaScript のイベント処理のための完璧なフックポイントであるのが、id 付きのグループです。コンポーネントのように <g> を扱いましょう:形状をまとめ、id を与え、単位として相互作用します。すべての子からのイベントを捉えるのが、グループ上のイベントリスナーです。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <!-- <g> can have ids for CSS targeting and JS selection -->
  <g id="button" class="interactive" data-action="save">
    <rect width="80" height="30" rx="5" fill="steelblue"/>
    <text x="40" y="20" text-anchor="middle" fill="white">Save</text>
  </g>

  <style>
    #button:hover rect { fill: royalblue; }
    #button { cursor: pointer; }
  </style>

  <script>
    document.getElementById("button").addEventListener("click", save);
  </script>
</svg>

グループ対 Symbol

再利用可能なアイコン向けに目的特化しているのが、<symbol> です。決して直接描画されず、独自の viewBox を持つため、<use> が独立にサイズ化できます。<defs> 内の <g> も機能しますが、viewBox の機能が欠けます。アイコンシステムのためには、<symbol> を推奨しましょう — 自動的に、拡縮とアスペクト比を扱うからです。

svg
<svg width="0" height="0" viewBox="0 0 0 0">
  <!-- <g> in <defs>: original is hidden, use can instantiate -->
  <defs>
    <g id="icon-g">
      <rect width="20" height="20" fill="red"/>
    </g>
  </defs>

  <!-- <symbol> is like <g> but supports viewBox and is never rendered -->
  <symbol id="icon-s" viewBox="0 0 20 20">
    <rect width="20" height="20" fill="blue"/>
  </symbol>

  <!-- Use with explicit size (symbol scales to fit) -->
  <use href="#icon-g" x="0" y="0"/>
  <use href="#icon-s" x="40" y="0" width="40" height="40"/>
</svg>
09

Use / Symbol / Defs

defs 要素

参照されるまで描画されない、再利用可能な定義を保持するのが、<defs> です:グラデーション、パターン、フィルタ、クリップパス、マスク、シンボル、グループです。描画される出力をきれいに保ち、意図を合図するのが、defs への配置です。直ちに描画されるのが、defs の外の何かです。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <defs>
    <!-- Anything in defs is defined but NOT rendered -->
    <linearGradient id="myGrad">
      <stop offset="0" stop-color="red"/>
      <stop offset="1" stop-color="blue"/>
    </linearGradient>

    <pattern id="myPattern" width="20" height="20">
      <circle cx="10" cy="10" r="5" fill="url(#myGrad)"/>
    </pattern>

    <g id="myShape">
      <rect width="40" height="40" rx="5"/>
    </g>
  </defs>

  <!-- Reference and render them -->
  <rect width="100" height="100" fill="url(#myPattern)"/>
  <use href="#myShape" x="120" y="30" fill="green"/>
</svg>

use 要素

定義された要素(g、symbol、任意の形状)を複製し描画するのが、<use> です。インスタンスを配置するのが、x/y です。(元のものが指定しなかった場合にのみ)元のものを <use> 上の fill/stroke が上書きするのが、CSS の継承です。インスタンスへ適用されるのが、transform です。SVG のスプライトが機能する方法が、これです。

svg
<svg width="300" height="100" viewBox="0 0 300 100">
  <defs>
    <g id="cloud">
      <circle cx="30" cy="50" r="20" fill="white"/>
      <circle cx="50" cy="45" r="25" fill="white"/>
      <circle cx="75" cy="50" r="20" fill="white"/>
    </g>
  </defs>

  <!-- Basic use -->
  <use href="#cloud"/>

  <!-- Positioned and styled -->
  <use href="#cloud" x="120" y="0" fill="lightgray"/>
  <use href="#cloud" x="200" y="10" transform="scale(0.5)" fill="silver"/>
</svg>

symbol 要素

独自の viewBox を持つ、再利用可能なグラフィックを定義するのが、<symbol> です。<g> と違い、決して直接描画されず、<use> 要素の寸法に合わせ拡縮します。CSS の color 経由で消費者が色を設定できるのが、fill='currentColor' です。SVG のアイコンシステムの標準のパターンが、これです。

svg
<!-- In a hidden sprite file or <defs> -->
<svg width="0" height="0" style="position:absolute">
  <symbol id="heart" viewBox="0 0 32 32">
    <path d="M16 28 C 4 18, 4 8, 12 8 C 14 8, 16 10, 16 12
             C 16 10, 18 8, 20 8 C 28 8, 28 18, 16 28 Z"
          fill="currentColor"/>
  </symbol>

  <symbol id="star" viewBox="0 0 32 32">
    <polygon points="16,2 20,12 31,12 22,19 25,30 16,23 7,30 10,19 1,12 12,12"
             fill="currentColor"/>
  </symbol>
</svg>

<!-- Usage: size with width/height, color with CSS -->
<svg width="24" height="24"><use href="#heart"/></svg>
<svg width="48" height="48"><use href="#star" style="color: gold"/></svg>

外部 SVG の参照

href='file.svg#id' 経由で、外部の SVG ファイル内のシンボルを参照できるのが、<use> です。しかし、一貫しないのが(IE なし、CORS の制限)、ブラウザの対応であり、file:// で壊れます。信頼できるアプローチが、HTML の上部へ隠れた SVG のスプライトをインライン化し、同じ文書内でシンボルを参照することです。

svg
<!-- Reference a symbol in an external .svg file -->
<svg width="24" height="24">
  <use href="icons.svg#heart"/>
</svg>

<!-- The external file (icons.svg) would contain: -->
<!-- <svg xmlns="http://www.w3.org/2000/svg" style="display:none"> -->
<!--   <symbol id="heart" viewBox="0 0 32 32">...</symbol> -->
<!-- </svg> -->

<!-- Note: external references have limited browser support -->
<!-- and don't work with file:// protocol. Inline is more reliable. -->
<!-- For production, inline the sprite at the top of your HTML body. -->

Use 属性の上書き

元の形状がプレゼンテーション属性(fill など)を省略するなら、<use> がそれを設定でき — インスタンスが値を継承します。元のものが fill を指定すれば、無視されるのが、use の fill です(CSS の継承に勝るのが、プレゼンテーション属性です)。カスタマイズ可能なシンボルを作るには、上書きしてほしい属性を省きましょう。

svg
<svg width="300" height="100" viewBox="0 0 300 100">
  <defs>
    <!-- Shape without explicit fill — inherits from use -->
    <circle id="ball" cx="20" cy="20" r="15"/>
  </defs>

  <!-- Each use can set its own fill -->
  <use href="#ball" fill="red"/>
  <use href="#ball" x="50" fill="green"/>
  <use href="#ball" x="100" fill="blue" stroke="black" stroke-width="2"/>
</svg>

Symbol のネストとスプライト

SVG のアイコンのための本番のパターンが、これです:<symbol> としてすべてのアイコンを含む、文書の上部の 1 つの隠れたスプライト SVG で、どこででも描画するのが、<use> です。テキストの色をアイコンが継承するのが、currentColor です。サイズを制御するのが、CSS です。初回ロード後にキャッシュされ、すべてのページで速いのが、スプライトです。

svg
<!-- A complete inline SVG sprite system -->
<svg style="display:none" aria-hidden="true">
  <symbol id="icon-home" viewBox="0 0 24 24">
    <path d="M12 3 L2 12 H5 V21 H10 V14 H14 V21 H19 V12 H22 Z"/>
  </symbol>
  <symbol id="icon-search" viewBox="0 0 24 24">
    <circle cx="11" cy="11" r="7" fill="none" stroke="currentColor" stroke-width="2"/>
    <line x1="16" y1="16" x2="21" y2="21" stroke="currentColor" stroke-width="2"/>
  </symbol>
</svg>

<!-- Reference anywhere in HTML -->
<svg class="icon"><use href="#icon-home"/></svg>
<svg class="icon"><use href="#icon-search"/></svg>

<style>
  .icon { width: 24px; height: 24px; fill: currentColor; }
</style>
10

フィルタ

フィルタの基本

グラフィックを処理する、1 つ以上のフィルタプリミティブ(fe* 要素)を含むのが、<filter> です。要素自身の描画を取るのが、in='SourceGraphic' です。適用するのが、filter='url(#id)' です。高コストになり得るのが、フィルタであるため — 大きい背景でなく、小さい要素に控えめに使いましょう。

svg
<svg width="200" height="120" viewBox="0 0 200 120">
  <defs>
    <filter id="blur1">
      <!-- feGaussianBlur: stdDeviation is the blur radius -->
      <feGaussianBlur in="SourceGraphic" stdDeviation="3"/>
    </filter>
  </defs>

  <!-- Without filter -->
  <text x="10" y="30" font-size="24" fill="red">Sharp</text>

  <!-- With filter -->
  <text x="10" y="70" font-size="24" fill="red"
        filter="url(#blur1)">Blurred</text>
</svg>

ドロップシャドウ

feOffset(移動)、feGaussianBlur(柔らかく)、feFlood(色)、feComposite(影への色の適用)、feMerge(元の下への影のレイヤー化)を組み合わせるのが、ドロップシャドウです。拡大されなければならず、さもなければ影がクリップされるのが、フィルタの x/y/width/height(デフォルト -10%〜110%)です。

svg
<svg width="200" height="120" viewBox="0 0 200 120">
  <defs>
    <filter id="shadow" x="-20%" y="-20%" width="140%" height="140%">
      <!-- Offset the source -->
      <feOffset in="SourceAlpha" dx="4" dy="4" result="offset"/>
      <!-- Blur the offset copy -->
      <feGaussianBlur in="offset" stdDeviation="3" result="blur"/>
      <!-- Color the shadow -->
      <feFlood flood-color="black" flood-opacity="0.5" result="color"/>
      <feComposite in="color" in2="blur" operator="in" result="shadow"/>
      <!-- Put shadow under the original -->
      <feMerge>
        <feMergeNode in="shadow"/>
        <feMergeNode in="SourceGraphic"/>
      </feMerge>
    </filter>
  </defs>

  <rect x="20" y="20" width="80" height="60" fill="white"
        filter="url(#shadow)"/>
</svg>

単純なドロップシャドウ(CSS)

インライン SVG 上の単純な影のために、SVG のフィルタを構築するより、はるかに簡単なのが、CSS の filter: drop-shadow() です。(box-shadow のようにバウンディングボックスでなく)形状の本物の輪郭を尊重します。CSS が表現できない、複雑なマルチステップの効果のためだけに、SVG のフィルタを使いましょう。

svg
<!-- Modern browsers: use CSS filter instead of SVG filter -->
<svg width="200" height="100" viewBox="0 0 200 100">
  <rect x="50" y="20" width="100" height="60" fill="white"
        style="filter: drop-shadow(4px 4px 4px rgba(0,0,0,0.5));"/>
</svg>

<!-- In CSS -->
<style>
  .shadowed { filter: drop-shadow(0 0 10px rgba(0,0,0,0.3)); }
</style>

<!-- CSS drop-shadow follows the shape's alpha, unlike box-shadow -->
<!-- which only shadows the bounding box -->

カラー行列

5x4 の行列経由で色を変換するのが(RGBA の入力、RGBA の出力)、feColorMatrix です。脱飽和するのが、0〜1 の値付きの type='saturate' で、度で hue を回転させるのが、type='hueRotate'、明るさを alpha へ変換するのが、type='luminanceToAlpha' です。SVG のコンテンツ上の、グレースケール、セピア、色の調整に有用です。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <defs>
    <!-- Convert to grayscale -->
    <filter id="grayscale">
      <feColorMatrix type="matrix"
        values="0.33 0.33 0.33 0 0
                0.33 0.33 0.33 0 0
                0.33 0.33 0.33 0 0
                0    0    0    1 0"/>
    </filter>

    <!-- Built-in saturation -->
    <filter id="desaturate">
      <feColorMatrix type="saturate" values="0"/>
    </filter>
  </defs>

  <image href="photo.jpg" width="100" height="100" filter="url(#grayscale)"/>
  <image href="photo.jpg" x="100" width="100" height="100" filter="url(#desaturate)"/>
</svg>

ライティング効果

2 次元形状の(alpha から導出された)高さマップ上の、3D のライティングをシミュレートするのが、feSpecularLighting と feDiffuseLighting です。深さを制御するのが、surfaceScale で、方向を設定するのが、光の要素(fePointLight、feDistantLight、feSpotLight)です。feComposite と組み合わせると、浮き出し、ベベル、3D テキスト効果が得られます。

svg
<svg width="200" height="120" viewBox="0 0 200 120">
  <defs>
    <filter id="emboss">
      <!-- Create a height map from the alpha -->
      <feGaussianBlur in="SourceAlpha" stdDeviation="2" result="blur"/>
      <!-- Lighting from upper-left -->
      <feSpecularLighting in="blur" surfaceScale="5"
                          specularConstant="0.8" specularExponent="20"
                          lighting-color="white" result="spec">
        <fePointLight x="-50" y="-50" z="200"/>
      </feSpecularLighting>
      <feComposite in="spec" in2="SourceGraphic"
                   operator="in" result="lit"/>
      <feComposite in="SourceGraphic" in2="lit" operator="arithmetic"
                   k1="0" k2="1" k3="1" k4="0"/>
    </filter>
  </defs>

  <text x="10" y="70" font-size="48" font-weight="bold"
        fill="gray" filter="url(#emboss)">3D</text>
</svg>

タービュランス(テクスチャ)

手続き的なノイズを生成するのが、feTurbulence です(fractal か turbulence のタイプ)。静的なもの、雲、水、紙の目のようなテクスチャに有用です。スケールを制御するのが、baseFrequency です(0.5 = 細かい、0.05 = 雲のような)。速度を代償に詳細を加えるのが、numOctaves です。効果のために、feColorMatrix か feDisplacementMap と組み合わせましょう。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <defs>
    <!-- feTurbulence generates Perlin noise -->
    <filter id="noise" x="0" y="0" width="100%" height="100%">
      <feTurbulence type="fractalNoise" baseFrequency="0.65"
                    numOctaves="3" stitchTiles="stitch"/>
      <feColorMatrix type="matrix"
        values="0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 0.1 0"/>
    </filter>
  </defs>

  <rect width="200" height="200" fill="steelblue"/>
  <rect width="200" height="200" filter="url(#noise)"/>

  <!-- type: "fractalNoise" or "turbulence" -->
  <!-- baseFrequency: lower = larger blobs, higher = finer grain -->
  <!-- numOctaves: more = more detail (slower) -->
</svg>
11

クリッピングとマスキング

Clip Path

ハードエッジの境界を定義するのが、clipPath です。内側のピクセルが見え、外側が隠れます。クリップの形状自体は描画されません。url(#id) 経由で参照するのが、clip-path です。二値であるのが(内外)、クリッピングです。ソフトな遷移には、マスクを使いましょう。クリップパスとしてのテキストが、クラシックな「テキストの中の画像」効果を作ります。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <defs>
    <!-- A clip path: only the inside is visible -->
    <clipPath id="circleClip">
      <circle cx="100" cy="100" r="80"/>
    </clipPath>
  </defs>

  <!-- The image is clipped to the circle -->
  <rect width="200" height="200" fill="steelblue"
        clip-path="url(#circleClip)"/>

  <!-- Any shape can be a clip path -->
  <clipPath id="textClip">
    <text x="100" y="120" font-size="80" text-anchor="middle"
          font-weight="bold">SVG</text>
  </clipPath>
  <rect width="200" height="200" fill="gold" clip-path="url(#textClip)"/>
</svg>

マスク

マスクが、(二値の)clip-path と違い、alpha をサポートします。完全に見えるのが、白い領域で、隠れるのが、黒い領域、部分的に透明なのが、グレーです。滑らかなフェードのために、マスクの内容としてグラデーションを使いましょう。クリップパスより重いが、ソフトな遷移と写真効果には不可欠なのが、マスクです。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <defs>
    <!-- A mask: white = visible, black = hidden, gray = partial -->
    <mask id="fadeMask">
      <linearGradient id="fadeGrad" x1="0" y1="0" x2="0" y2="1">
        <stop offset="0" stop-color="white"/>
        <stop offset="1" stop-color="black"/>
      </linearGradient>
      <rect width="200" height="200" fill="url(#fadeGrad)"/>
    </mask>
  </defs>

  <!-- The image fades from top to bottom -->
  <rect width="200" height="200" fill="red" mask="url(#fadeMask)"/>
</svg>

Clip Path の単位

クリップパスが各要素のバウンディングボックスへ拡縮するのが(座標 0〜1)、clipPathUnits='objectBoundingBox' です。そのため、1 つのクリップパスが、異なるサイズの形状に機能します。絶対の SVG 座標を使うのが、「userSpaceOnUse」(デフォルト)です。objectBoundingBox を使うのが、ほとんどの再利用可能なクリップです。

svg
<svg width="300" height="100" viewBox="0 0 300 100">
  <defs>
    <!-- userSpaceOnUse (default): clip coords in SVG units -->
    <clipPath id="clip1" clipPathUnits="userSpaceOnUse">
      <rect x="10" y="10" width="50" height="50"/>
    </clipPath>

    <!-- objectBoundingBox: coords are 0-1 relative to the element -->
    <clipPath id="clip2" clipPathUnits="objectBoundingBox">
      <rect x="0.1" y="0.1" width="0.8" height="0.8"/>
    </clipPath>
  </defs>

  <rect width="100" height="100" fill="red" clip-path="url(#clip1)"/>
  <rect x="100" width="100" height="80" fill="blue" clip-path="url(#clip2)"/>
  <rect x="200" width="100" height="60" fill="green" clip-path="url(#clip2)"/>
</svg>

CSS の clip-path

SVG なしで、基本形状(circle、ellipse、polygon、inset)を直接サポートし、url(#id) 経由で SVG の clipPath 要素を参照できるのが、CSS の clip-path です。SVG だけでなく、HTML の要素上でも機能します。mask-image 経由でモダンなブラウザがサポートするのも、CSS のマスキングです。

svg
<style>
  /* CSS clip-path works on SVG and HTML elements */
  .circle {
    clip-path: circle(50% at 50% 50%);
  }
  .triangle {
    clip-path: polygon(50% 0%, 100% 100%, 0% 100%);
  }
  /* Reference an SVG clipPath */
  .svg-clip {
    clip-path: url(#myClip);
  }
</style>

<svg width="200" height="100">
  <defs>
    <clipPath id="myClip">
      <circle cx="50" cy="50" r="40"/>
    </clipPath>
  </defs>
  <rect class="svg-clip" width="200" height="100" fill="purple"/>
</svg>

実用:テキストの中の画像

人気のデザインの技法であるのが、テキストへのグラデーションか画像のクリッピングです。<text> の要素を含むのが、clipPath で、文字の形状の内側でのみ見えるよう、クリップされた rect がグラデーションで満たされます。<image> でも機能し、マガジンスタイルのヘッダーのために、テキストの中に写真を置きましょう。

svg
<svg width="400" height="120" viewBox="0 0 400 120">
  <defs>
    <clipPath id="textShape">
      <text x="200" y="90" font-size="80" font-weight="900"
            text-anchor="middle" font-family="Arial">SUMMER</text>
    </clipPath>
  </defs>

  <!-- Background (visible only through the text) -->
  <rect width="400" height="120" fill="black"/>

  <!-- Image clipped to the text shape -->
  <rect width="400" height="120" fill="url(#sunsetGrad)"
        clip-path="url(#textShape)"/>

  <linearGradient id="sunsetGrad" x1="0" y1="0" x2="0" y2="1">
    <stop offset="0" stop-color="#ff6b6b"/>
    <stop offset="0.5" stop-color="#feca57"/>
    <stop offset="1" stop-color="#ff9ff3"/>
  </linearGradient>
</svg>
12

アニメーション(SMIL)

animate(基本)

時間をかけた属性の遷移を行うのが、<animate> です。ターゲットが、attributeName で、範囲を定義するのが、from/to、duration が、dur、永遠にループするのが、repeatCount='indefinite' です。宣言的であるのが(JS 不要)、SMIL のアニメーションで、IE を除くほとんどのブラウザで機能します。ターゲット要素の子として住むのが、アニメーションです。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <rect x="0" y="40" width="20" height="20" fill="red">
    <animate attributeName="x"
             from="0" to="180"
             dur="2s"
             repeatCount="indefinite"/>
  </rect>

  <!-- The rect moves from x=0 to x=180 over 2 seconds, forever -->
</svg>

animateTransform

transform 属性をアニメーション化するのが、<animateTransform> です。操作を選ぶのが、type です(rotate、scale、translate、skewX、skewY)。rotate のためには、「angle cx cy」が(中心点)、from/to です。JS なしで要素を回転させる方法が、これです。additive='sum' を使わない限り、要素ごとに 1 つの animateTransform しか動けません。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <rect x="80" y="80" width="40" height="40" fill="blue">
    <animateTransform attributeName="transform"
                      type="rotate"
                      from="0 100 100" to="360 100 100"
                      dur="3s"
                      repeatCount="indefinite"/>
  </rect>

  <!-- type can be: rotate, scale, translate, skewX, skewY -->
  <!-- For rotate, the values are "angle cx cy" -->
</svg>

animateMotion

パスに沿って要素を動かすのが、<animateMotion> です。パスを参照するのが、<mpath href='#id'> で、直接 path を定義するのが、代わりです。要素が移動の方向を向くよう整列させるのが、rotate='auto' です。矢印、車、キャラクタには不可欠です。JS なしでパスベースのアニメーションを行う SVG の方法が、これです。

svg
<svg width="200" height="150" viewBox="0 0 200 150">
  <defs>
    <path id="motionPath" d="M 10 75 Q 100 0, 190 75" fill="none"/>
  </defs>

  <!-- A circle follows the path -->
  <circle r="10" fill="red">
    <animateMotion dur="3s" repeatCount="indefinite">
      <mpath href="#motionPath"/>
    </animateMotion>
  </circle>

  <!-- Show the path for reference -->
  <use href="#motionPath" stroke="gray" stroke-width="1"/>

  <!-- rotate="auto" makes the element face the direction of motion -->
  <circle r="5" fill="blue">
    <animateMotion dur="3s" repeatCount="indefinite" rotate="auto">
      <mpath href="#motionPath"/>
    </animateMotion>
  </circle>
</svg>

キーフレームとイージング

マルチステップのアニメーションのためには、(セミコロン区切りの)values、(0〜1 の分数の)keyTimes、(セグメントごとのベジェのイージングである)keySplines を使いましょう。イージングを可能にするのが、calcMode='spline' で、デフォルトが「linear」です。純粋な SVG で、CSS のキーフレームアニメーションを映し返すのが、これです。滑らかなイージングで、往復するのが、rect です。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <rect x="0" y="40" width="20" height="20" fill="green">
    <animate attributeName="x"
             values="0; 80; 180; 80; 0"
             keyTimes="0; 0.25; 0.5; 0.75; 1"
             keySplines="0.5 0 0.5 1; 0 0 1 1; 0.5 0 0.5 1; 0 0 1 1"
             calcMode="spline"
             dur="4s"
             repeatCount="indefinite"/>
  </rect>

  <!-- values: the animated values at each keyTime -->
  <!-- keyTimes: 0-1 fractions of dur (semicolon-separated) -->
  <!-- keySplines: cubic-bezier easing between each pair -->
  <!-- calcMode: "discrete", "linear", "paced", or "spline" -->
</svg>

begin、end、トリガー

時間のオフセット(2s)、イベント(click、mouseenter)、か別のアニメーションのイベントへの参照(anim1.end、anim1.begin+1s)であり得るのが、begin です。アニメーション終了後、最終値を保持するのが(さもなければ、戻って跳ねます)、fill='freeze' です。これで、JS なしの、クリックトリガーとチェーンされたアニメーションが可能になります。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <!-- begin: when to start (time or event) -->
  <rect x="10" y="10" width="30" height="30" fill="red">
    <animate attributeName="width" from="30" to="100"
             dur="1s" begin="2s" fill="freeze"/>
  </rect>

  <!-- begin on a click event -->
  <rect x="10" y="60" width="30" height="30" fill="blue" id="trigger">
    <animate attributeName="x" from="10" to="150"
             dur="1s" begin="click" fill="freeze"/>
  </rect>

  <!-- begin when another animation ends -->
  <rect x="10" y="80" width="30" height="10" fill="green">
    <animate attributeName="x" from="10" to="150"
             dur="1s" begin="trigger.click+1s" fill="freeze"/>
  </rect>
</svg>

CSS のアニメーションの代替

Web ページでのインライン SVG のためには、SMIL よりしばしば簡単でより良いツールがあるのが、CSS のアニメーションです。transform-origin: center が、SVG のキャンバスでなく要素を参照するよう、transform-box: fill-box を使いましょう。スタンドアロンの SVG ファイル(CSS が利用不可)のためと、パスベースのモーションのために、有用であり続けるのが、SMIL です。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <style>
    .pulse {
      animation: pulse 1.5s ease-in-out infinite;
      transform-origin: center;
      transform-box: fill-box;
    }
    @keyframes pulse {
      0%, 100% { transform: scale(1); opacity: 1; }
      50% { transform: scale(1.2); opacity: 0.7; }
    }
  </style>

  <circle class="pulse" cx="100" cy="50" r="20" fill="red"/>
</svg>

<!-- CSS animations are more maintainable for web pages -->
<!-- SMIL is better for standalone .svg files -->
13

イベント

マウスイベント

標準の DOM イベントをサポートするのが、SVG の要素です:click、mouseenter、mouseleave、mousemove、mousedown、mouseup、dblclick です。HTML の要素のように、addEventListener を使いましょう。ハンドラ内の「this」が、SVG 要素を参照します。リアクティブにプロパティを変えるには、setAttribute を使いましょう。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <rect id="box" x="10" y="10" width="80" height="80" fill="steelblue"/>

  <script>
    var box = document.getElementById("box");
    box.addEventListener("click", function (e) {
      alert("Clicked at " + e.clientX + "," + e.clientY);
    });
    box.addEventListener("mouseenter", function () {
      this.setAttribute("fill", "tomato");
    });
    box.addEventListener("mouseleave", function () {
      this.setAttribute("fill", "steelblue");
    });
  </script>
</svg>

タッチイベント

touchstart、touchmove、touchend を SVG がサポートします。createSVGPoint と getScreenCTM().inverse() を使い、画面の座標を SVG の座標へ変換しましょう — SVG が拡縮、レスポンシブのときには不可欠です。スクロールのようなジェスチャの干渉を防ぐのが、touchstart 上の preventDefault() です。

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <circle id="touch" cx="100" cy="100" r="30" fill="purple"/>

  <script>
    var circle = document.getElementById("touch");
    circle.addEventListener("touchstart", function (e) {
      e.preventDefault();  // prevent scrolling
      this.setAttribute("fill", "orange");
    });
    circle.addEventListener("touchend", function () {
      this.setAttribute("fill", "purple");
    });
    // touchmove for dragging
    circle.addEventListener("touchmove", function (e) {
      var touch = e.touches[0];
      var pt = svg.createSVGPoint();
      pt.x = touch.clientX; pt.y = touch.clientY;
      var svgP = pt.matrixTransform(svg.getScreenCTM().inverse());
      this.setAttribute("cx", svgP.x);
      this.setAttribute("cy", svgP.y);
    });
  </script>
</svg>

座標の変換

SVG の viewBox がピクセルサイズと異なるとき、画面の座標が、SVG の座標へ 1:1 にマッピングしません。viewBox、CSS の拡縮、そして祖先要素上の transform さえ考慮し、正しく変換するのが、createSVGPoint + getScreenCTM().inverse() です。正確なクリック検出には、不可欠です。

svg
<svg width="500" height="300" viewBox="0 0 1000 600" id="mysvg">
  <rect width="1000" height="600" fill="lightblue"/>

  <script>
    var svg = document.getElementById("mysvg");
    svg.addEventListener("click", function (e) {
      // Convert screen (clientX/Y) to SVG user coordinates
      var pt = svg.createSVGPoint();
      pt.x = e.clientX;
      pt.y = e.clientY;

      // getScreenCTM maps SVG coords to screen; inverse maps back
      var svgPoint = pt.matrixTransform(
        svg.getScreenCTM().inverse()
      );

      console.log("SVG coords:", svgPoint.x, svgPoint.y);
      // This accounts for viewBox scaling and CSS sizing
    });
  </script>
</svg>

イベント委譲

より効率的であり、動的に加えられた形状を自動的に扱うのが、(子の多くのリスナーの代わりの、親グループ上の 1 つのリスナーである)イベント委譲です。クリックされた形状が、e.target で、リスナーを持つ要素が、e.currentTarget です。形状ごとのメタデータを保存するのに、data-* 属性を使いましょう。

svg
<svg width="300" height="100" viewBox="0 0 300 100">
  <g id="shapes">
    <circle cx="50" cy="50" r="30" fill="red" data-name="circle1"/>
    <rect x="100" y="20" width="60" height="60" fill="blue" data-name="rect1"/>
    <polygon points="220,20 280,20 250,80" fill="green" data-name="tri1"/>
  </g>

  <script>
    // One listener on the parent group handles all children
    document.getElementById("shapes").addEventListener("click", function (e) {
      var target = e.target;
      var name = target.getAttribute("data-name");
      console.log("Clicked:", name, target.tagName);
      // e.target is the actual shape; e.currentTarget is the group
    });
  </script>
</svg>

ドラッグのインタラクション

クラシックな SVG のドラッグパターンが、これです:フラグを設定するのが、mousedown で、(変換された SVG 座標を使い)要素の位置を更新するのが、mousemove、フラグを消去するのが、mouseup です。カーソルが形状を去ってもドラッグが続くよう、(要素でなく)SVG へ mousemove/mouseup を付けましょう。SVG ベースのエディタの基礎が、これです。

svg
<svg width="400" height="300" viewBox="0 0 400 300" id="canvas">
  <circle id="draggable" cx="200" cy="150" r="30" fill="orange" cursor="grab"/>

  <script>
    var circle = document.getElementById("draggable");
    var svg = document.getElementById("canvas");
    var dragging = false;

    function getSVGPoint(e) {
      var pt = svg.createSVGPoint();
      pt.x = e.clientX; pt.y = e.clientY;
      return pt.matrixTransform(svg.getScreenCTM().inverse());
    }

    circle.addEventListener("mousedown", function () {
      dragging = true;
      this.setAttribute("cursor", "grabbing");
    });
    svg.addEventListener("mousemove", function (e) {
      if (!dragging) return;
      var p = getSVGPoint(e);
      circle.setAttribute("cx", p.x);
      circle.setAttribute("cy", p.y);
    });
    svg.addEventListener("mouseup", function () {
      dragging = false;
      circle.setAttribute("cursor", "grab");
    });
  </script>
</svg>
14

JavaScript の DOM

要素の作成

document.createElementNS(namespace, tagName) で作成しなければならないのが、SVG の要素です。createElement が SVG のために機能しません(未知の HTML 要素を作ります)。SVG の名前空間が、「http://www.w3.org/2000/svg」です。プロパティのためには、setAttribute を。動的な SVG 生成の基礎が、これです。

svg
<svg id="canvas" width="200" height="200" viewBox="0 0 200 200">
  <script>
    var svg = document.getElementById("canvas");
    var NS = "http://www.w3.org/2000/svg";

    // createElementNS is required for SVG elements
    var circle = document.createElementNS(NS, "circle");
    circle.setAttribute("cx", "100");
    circle.setAttribute("cy", "100");
    circle.setAttribute("r", "50");
    circle.setAttribute("fill", "red");
    svg.appendChild(circle);

    // Create a path
    var path = document.createElementNS(NS, "path");
    path.setAttribute("d", "M 10 10 L 100 100");
    path.setAttribute("stroke", "black");
    svg.appendChild(path);
  </script>
</svg>

要素の修正

SVG のプレゼンテーション属性(fill、stroke、width など)のためには、setAttribute/getAttribute を使いましょう。ブラウザをまたいで信頼して機能するのが、classList です。CSS のプロパティへマッピングされるため、style.fill の設定が機能します。SVG のための innerHTML は避け(ブラウザ間で一貫しません)、createElementNS で DOM を構築しましょう。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <rect id="r" x="10" y="10" width="50" height="50" fill="blue"/>

  <script>
    var r = document.getElementById("r");

    // Change attributes
    r.setAttribute("fill", "red");
    r.setAttribute("width", "80");

    // Get attribute values
    var w = r.getAttribute("width");  // "80"

    // Remove attributes
    r.removeAttribute("fill");

    // Class manipulation (use classList, not className for SVG in some browsers)
    r.classList.add("highlight");
    r.classList.toggle("active");

    // Style (use setAttribute for presentation attributes)
    r.style.fill = "green";  // works via CSS
  </script>
</svg>

幾何の読み取り

(transform を無視して)SVG のユーザー単位でのバウンディングボックスを返すのが、getBBox() です。(すべての transform と CSS の後)画面の座標を返すのが、getBoundingClientRect() です。path/line の長さを与えるのが、getTotalLength() で、距離 d の点を返すのが、getPointAtLength(d) です。パスベースのアニメーションとヒットテストには不可欠です。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <rect id="r" x="10" y="10" width="80" height="50" fill="blue"/>

  <script>
    var r = document.getElementById("r");

    // Get bounding box in SVG user units
    var bbox = r.getBBox();
    console.log(bbox.x, bbox.y, bbox.width, bbox.height);

    // Get bounding box in screen coordinates (after transforms)
    var cbox = r.getBoundingClientRect();
    console.log(cbox.left, cbox.top, cbox.width, cbox.height);

    // Total length of a path or line
    var path = document.querySelector("path");
    var len = path.getTotalLength();
    var point = path.getPointAtLength(len / 2);  // midpoint
  </script>
</svg>

Dataset と data 属性

HTML と同様に、data-* 属性と dataset プロパティを、SVG の要素がサポートします。インタラクティブなアプリのための、形状にデータを関連付けるきれいな方法が、これです。視覚的な属性を汚染せず、ノードの ID、ラベル、状態を保存しましょう。読み取りが element.dataset.key で、同じで設定しましょう。

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <circle cx="50" cy="50" r="20" fill="red"
          data-id="123" data-label="node"/>

  <script>
    var circle = document.querySelector("circle");

    // dataset reads data-* attributes
    console.log(circle.dataset.id);     // "123"
    console.log(circle.dataset.label);  // "node"

    // Set data attributes
    circle.dataset.selected = "true";  // adds data-selected="true"

    // Use for storing state
    circle.dataset.visits = "0";
    circle.dataset.visits = String(+circle.dataset.visits + 1);
  </script>
</svg>

動的なパスの生成

カスタムチャートの基礎であるのが、SVG の動的な生成です。データから M/L コマンドを連結することで、path の d 属性を構築し、createElementNS で要素を作りましょう。チャートライブラリなしで、完全な制御を与えるのが、このアプローチです。複雑な可視化のためには、このパターンをエレガントに包む、D3.js を考えましょう。

svg
<svg width="300" height="150" viewBox="0 0 300 150" id="chart">
  <script>
    var NS = "http://www.w3.org/2000/svg";
    var svg = document.getElementById("chart");
    var data = [10, 50, 30, 80, 45, 90, 25];

    // Build a path string from data points
    var d = "M 0 " + (150 - data[0]);
    for (var i = 1; i < data.length; i++) {
      d += " L " + (i * 40) + " " + (150 - data[i]);
    }

    var path = document.createElementNS(NS, "path");
    path.setAttribute("d", d);
    path.setAttribute("fill", "none");
    path.setAttribute("stroke", "steelblue");
    path.setAttribute("stroke-width", "2");
    svg.appendChild(path);

    // Add dots at each point
    data.forEach(function (val, i) {
      var c = document.createElementNS(NS, "circle");
      c.setAttribute("cx", i * 40);
      c.setAttribute("cy", 150 - val);
      c.setAttribute("r", 3);
      c.setAttribute("fill", "red");
      svg.appendChild(c);
    });
  </script>
</svg>

パフォーマンスのヒント

パフォーマンスのためには:1 リフローでの DocumentFragment による DOM 挿入のバッチ化、JS アニメーションのための requestAnimationFrame(表示のリフレッシュへ同期)、密なループでの属性のクエリの回避(値のキャッシュ)、です。数百の要素まで、SVG が優れ、数千の(パーティクル、密なプロット)ためには、Canvas か WebGL がより速いです。

svg
<script>
  // Batch DOM operations with document fragments
  var fragment = document.createDocumentFragment();
  for (var i = 0; i < 1000; i++) {
    var c = document.createElementNS(NS, "circle");
    c.setAttribute("cx", i);
    c.setAttribute("cy", 50);
    c.setAttribute("r", 2);
    fragment.appendChild(c);
  }
  svg.appendChild(fragment);  // one reflow, not 1000

  // Use requestAnimationFrame for animations
  function animate() {
    element.setAttribute("cx", +element.getAttribute("cx") + 1);
    requestAnimationFrame(animate);
  }
  animate();

  // For many elements, consider <canvas> instead (faster)
  // SVG slows down with thousands of nodes due to DOM overhead
</script>
15

レスポンシブ SVG(ViewBox)

viewBox の基本

内部の座標系を定義するのが、viewBox='minX minY width height' です。ビューをパンするのが、最初の 2 つの値で、ズームするのが、最後の 2 つです。この領域が width/height に合うよう、SVG が拡縮します。描画の座標が、描画サイズから切り離されます — 任意のスケールで、100x100 か 1920x1080 のボックスの中で、1 回描画します。

svg
<!-- viewBox="minX minY width height" -->
<svg viewBox="0 0 100 100" width="200" height="200">
  <!-- A circle at center of a 100x100 coordinate system -->
  <circle cx="50" cy="50" r="50" fill="blue"/>
</svg>

<!-- viewBox shifts the visible area -->
<svg viewBox="50 50 50 50" width="200" height="200">
  <!-- Now showing only the bottom-right quadrant -->
  <!-- The same circle, but zoomed in 2x on that corner -->
  <circle cx="50" cy="50" r="50" fill="blue"/>
</svg>

preserveAspectRatio

アスペクト比が異なるとき、viewBox が要素にどう合うかを制御するのが、preserveAspectRatio です。完全に合い、余りがレターボックス化されるのが、「meet」(デフォルト)で、完全に満たし溢れを切り取るのが、「slice」、引き伸ばし歪めるのが、「none」です。整列を制御するのが、xMidYMid の部分です:両軸のために、Min/Mid/Max です。

svg
<!-- Default: preserve aspect ratio, center, letterbox -->
<svg viewBox="0 0 100 50" width="200" height="200"
     preserveAspectRatio="xMidYMid meet">
  <rect width="100" height="50" fill="blue"/>
</svg>

<!-- "slice": fill entirely, crop overflow -->
<svg viewBox="0 0 100 50" width="200" height="200"
     preserveAspectRatio="xMidYMid slice">
  <rect width="100" height="50" fill="red"/>
</svg>

<!-- "none": stretch to fill (distorts) -->
<svg viewBox="0 0 100 50" width="200" height="200"
     preserveAspectRatio="none">
  <rect width="100" height="50" fill="green"/>
</svg>

完全にレスポンシブな SVG

レスポンシブな SVG のためには:width/height 属性を省き、viewBox を設定し、CSS でサイズを制御しましょう(width: 100%、height: auto)。アスペクト比を保ちつつ、SVG がコンテナへ拡縮します。インライン SVG のベースラインのギャップを取り除くのが、display: block です。レスポンシブなレイアウトでの流動的な SVG の、標準のパターンが、これです。

svg
<!-- Omit width/height, set viewBox, use CSS to size -->
<svg viewBox="0 0 100 100" style="width: 100%; height: auto; display: block;">
  <circle cx="50" cy="50" r="50" fill="orange"/>
</svg>

<!-- In a container with max-width -->
<div style="max-width: 500px; margin: auto;">
  <svg viewBox="0 0 400 300" style="width: 100%; height: auto;">
    <rect width="400" height="300" fill="steelblue"/>
  </svg>
</div>

ネストした SVG と overflow

独自の viewBox と preserveAspectRatio を持つ独立のビューポートを作るのが、ネストした <svg> 要素です。固定のアスペクトのパネルを持つチャートや UI コンポーネントに強力です。ネストしたビューポートの外へコンテンツが描画できるのが(デフォルトは hidden)、overflow='visible' です。独立に、そのコンテンツを拡縮できるのが、各ネストした svg です。

svg
<svg width="300" height="200" viewBox="0 0 300 200">
  <!-- Nested SVG creates a new viewport -->
  <svg x="10" y="10" width="100" height="100" viewBox="0 0 50 50">
    <circle cx="25" cy="25" r="25" fill="red"/>
  </svg>

  <!-- overflow="hidden" (default) clips content outside -->
  <svg x="120" y="10" width="100" height="100" viewBox="0 0 50 50"
       overflow="visible">
    <circle cx="25" cy="25" r="30" fill="blue"/>
  </svg>

  <!-- Each nested svg can have its own preserveAspectRatio -->
  <svg x="230" y="10" width="60" height="100" viewBox="0 0 50 50"
       preserveAspectRatio="xMidYMid slice">
    <circle cx="25" cy="25" r="25" fill="green"/>
  </svg>
</svg>

流動的なテキストのサイジング

viewBox を持つ SVG 内のフォントサイズが、SVG と共に拡縮します。800px 幅で表示される、400 幅の viewBox 内の 20px のフォントが、40px で描画されます。(SVG でなく)ブラウザのビューポートへテキストをレスポンシブにさせるには、style 属性で、CSS のビューポートの単位(vw、vh)を使いましょう。SVG の見出しが流動的に拡縮する方法が、これです。

svg
<svg viewBox="0 0 400 100" style="width:100%;height:auto;">
  <style>
    /* Use viewBox units for font-size — scales with the SVG */
    text { font-size: 20px; }
    /* Note: 'px' here means SVG user units, not CSS px */
  </style>

  <text x="200" y="50" text-anchor="middle">Scales with SVG</text>
</svg>

<!-- For truly responsive text relative to viewport, use CSS: -->
<svg viewBox="0 0 400 100" style="width:100%;height:auto;">
  <text x="200" y="50" text-anchor="middle"
        style="font-size: 5vw;">5% of viewport width</text>
</svg>

<!-- Or use container queries / media queries on the SVG element -->

アスペクト比の制御

予測可能なレスポンシブの挙動のために、SVG 上の width/height 100% と、コンテナ上の CSS の aspect-ratio を組み合わせましょう。SVG がロードされる前にスペースを確保することで、レイアウトシフト(CLS)を防ぎます。コンテンツが歪まないよう、viewBox がアスペクト比に一致します。レスポンシブな SVG の埋め込みのための、モダンなベストプラクティスが、これです。

svg
<!-- Use CSS aspect-ratio for consistent sizing -->
<div style="width: 100%; max-width: 600px; aspect-ratio: 16/9;">
  <svg viewBox="0 0 1600 900" style="width:100%;height:100%;">
    <rect width="1600" height="900" fill="black"/>
    <text x="800" y="450" text-anchor="middle" dominant-baseline="middle"
          fill="white" font-size="48">16:9 Container</text>
  </svg>
</div>

<!-- aspect-ratio ensures the container keeps proportions -->
<!-- even before the SVG loads, preventing layout shift -->
16

SVG 対 Canvas

描画モデル

保持モードであるのが、SVG です。すべての形状が、後に検査、スタイル、再アニメーションできる DOM 要素です。即時モードであるのが、Canvas です。ピクセルを描く draw コマンドを発行し、オブジェクトとして形状が残りません。インタラクティブな UI には SVG がより良く、数千の動的なピクセルには、Canvas がより良いです。

svg
<!-- SVG: retained mode (DOM-based) -->
<svg width="200" height="100">
  <circle cx="50" cy="50" r="30" fill="red"/>
  <!-- Each element is a DOM node, accessible via JS -->
</svg>

<!-- Canvas: immediate mode (pixel-based) -->
<canvas id="c" width="200" height="100"></canvas>
<script>
  var ctx = document.getElementById("c").getContext("2d");
  ctx.beginPath();
  ctx.arc(50, 50, 30, 0, Math.PI * 2);
  ctx.fillStyle = "red";
  ctx.fill();
  // Pixels are drawn; the circle isn't an object anymore
</script>

SVG を使うとき

SVG を選ぶとき:解像度非依存のグラフィックス(アイコン、ロゴ)、アクセシビリティ(DOM をスクリーンリーダーが走査します)、インタラクティビティ(形状ごとのイベント)、SEO(選択可能なテキスト)、中程度の要素数(数百まで)です。テキストであり(gzip が良く効きます)、デザインツールで編集可能なのが、SVG のファイルです。

svg
<!-- SVG is ideal for:
     - Icons and logos (crisp at any size)
     - Charts with few elements (D3.js)
     - Interactive diagrams (clickable shapes)
     - Illustrations with editable layers
     - Accessibility-required graphics
-->
<svg viewBox="0 0 24 24" width="48" height="48">
  <path d="M12 2 L2 22 H22 Z" fill="triangle"/>
</svg>
<!-- Stays sharp whether displayed at 16px or 1024px -->
<!-- Each part can have its own click handler -->
<!-- Screen readers can access <title> and <desc> -->

Canvas を使うとき

Canvas を選ぶとき:高い要素数(数千の形状)、フレームごとの再描画(ゲーム、パーティクル)、ピクセル操作(フィルタ、効果)、DOM のアクセシビリティを必要としないとき、です。素のピクセルのスループットには Canvas がより速いですが、個々の形状レベルでのアクセシブルかインタラクティブにするのが、より難しいです。

svg
<!-- Canvas is ideal for:
     - Games (hundreds of sprites per frame)
     - Particle systems
     - Real-time image processing
     - Heatmaps with thousands of cells
     - Physics simulations
-->
<canvas id="particles" width="800" height="600"></canvas>
<script>
  var ctx = document.getElementById("particles").getContext("2d");
  var particles = [];
  for (var i = 0; i < 5000; i++) {
    particles.push({ x: Math.random()*800, y: Math.random()*600 });
  }
  function draw() {
    ctx.clearRect(0, 0, 800, 600);
    particles.forEach(function (p) {
      ctx.fillRect(p.x, p.y, 2, 2);
    });
    requestAnimationFrame(draw);
  }
  draw();
</script>

パフォーマンスの比較

要素数と共に劣化するのが、SVG のパフォーマンスです。イベント処理、スタイリング、レイアウトを持つ DOM ノードが、各形状であるためです。形状数にかかわらず、フレームごとの一定のオーバーヘッドを持つのが、Canvas です。複雑さに依存して、500〜2000 要素の周りにあるのが、交差です。静的か軽くアニメーション化されたグラフィックスには、SVG で構いません。密なリアルタイムのシーンには、Canvas を。

svg
<!-- SVG DOM overhead grows with element count -->
<!-- 100 circles: SVG ~0.1ms, Canvas ~0.1ms (both fine) -->
<!-- 1000 circles: SVG ~10ms, Canvas ~1ms (Canvas pulls ahead) -->
<!-- 10000 circles: SVG ~500ms+, Canvas ~10ms (SVG struggles) -->

<!-- SVG advantages:
     - No redraw needed for CSS changes (browser handles it)
     - Hardware-accelerated transforms
     - Only changed elements re-render (incremental)
-->
<!-- Canvas advantages:
     - Constant redraw cost regardless of history
     - No DOM memory overhead per shape
     - Direct pixel access (getImageData, putImageData)
-->

ハイブリッドのアプローチ

両方を組み合わせましょう:密で頻繁に再描画されるレイヤーのための Canvas(ヒートマップ、パーティクル)と、インタラクティブな UI のために重ねられる SVG(ツールチップ、選択ハンドル、ラベル)です。Canvas が重いピクセルの仕事を扱う間、鮮明でアクセシブルであり続けるのが、SVG のレイヤーです。Leaflet のようなマッピングライブラリと、ECharts のようなチャートツールが、このパターンを使います。

svg
<!-- SVG for UI chrome, Canvas for dense content -->
<div style="position:relative; width:800px; height:600px;">
  <!-- Canvas renders the heatmap (fast for thousands of cells) -->
  <canvas width="800" height="600" style="position:absolute; top:0; left:0;">
  </canvas>

  <!-- SVG overlay for interactive tooltips and selection -->
  <svg width="800" height="600" viewBox="0 0 800 600"
       style="position:absolute; top:0; left:0;">
    <g id="overlay"></g>
  </svg>
</div>

<script>
  // Draw heatmap on canvas (performant)
  // Add hover tooltips as SVG elements (accessible, styled)
</script>

アクセシビリティの比較

本質的によりアクセシブルであるのが、SVG です。走査可能なのが DOM で、選択可能で検索可能なのがテキスト、説明を提供するのが、<title>/<desc> です。余分な仕事を必要とするのが、Canvas です。role/aria-label を加え、<canvas> タグの内側にテキストのフォールバックのコンテンツを提供しなければなりません。チャートとデータの可視化のためには、大きな利点が、SVG のアクセシビリティです。

svg
<!-- SVG: screen readers traverse the DOM -->
<svg role="img" aria-label="Sales chart showing 20% growth">
  <title>Sales Chart</title>
  <desc>Bar chart with 5 quarters, Q3 highest at $2M</desc>
  <rect .../>  <!-- each bar is a DOM element -->
</svg>
<!-- Text in SVG is selectable and searchable -->

<!-- Canvas: just pixels to a screen reader -->
<canvas role="img" aria-label="Sales chart showing 20% growth">
  <!-- Must provide text fallback inside the canvas tag -->
  Sales chart: Q1 $1M, Q2 $1.3M, Q3 $2M, Q4 $1.8M
</canvas>
<!-- No DOM, no selectable text, harder to make accessible -->
17

SVG スプライト

インラインスプライトのセットアップ

ページの上部の隠れた SVG の内側に、<symbol> 要素として、すべてのアイコンを定義しましょう。独自の viewBox と id を、各シンボルが持ちます。1 回ロードされ、セッションの間キャッシュされるのが、スプライトです。fill/stroke のための currentColor の使用により、各使用が、周囲のテキストの色を継承するため、テーマ化が自明になります。

svg
<!-- Place this hidden SVG at the top of your HTML body -->
<svg xmlns="http://www.w3.org/2000/svg" style="display:none" aria-hidden="true">
  <symbol id="icon-home" viewBox="0 0 24 24">
    <path d="M12 3 L2 12 H5 V21 H10 V14 H14 V21 H19 V12 H22 Z"/>
  </symbol>
  <symbol id="icon-user" viewBox="0 0 24 24">
    <circle cx="12" cy="8" r="4"/>
    <path d="M4 21 C 4 16, 8 14, 12 14 C 16 14, 20 16, 20 21 Z"/>
  </symbol>
  <symbol id="icon-search" viewBox="0 0 24 24">
    <circle cx="11" cy="11" r="7" fill="none" stroke="currentColor" stroke-width="2"/>
    <line x1="16" y1="16" x2="21" y2="21" stroke="currentColor" stroke-width="2"/>
  </symbol>
</svg>

スプライトのアイコンの使用

アイコンをインスタンス化するのが、各 <use> です。デフォルトのサイズを設定するのが、CSS の .icon クラスで、バリアントのために上書きするのが、サブクラスです。fill='currentColor' をシンボルが使うため、CSS の color プロパティに従うのが、アイコンの色です。ボタン上に color を設定すれば、そのアイコンが一致します。主要なアイコンシステム(GitHub、Bootstrap)が機能する方法が、これです。

svg
<!-- Reference any icon with <use> -->
<svg class="icon"><use href="#icon-home"/></svg>
<svg class="icon"><use href="#icon-user"/></svg>
<svg class="icon icon-large"><use href="#icon-search"/></svg>

<style>
  .icon {
    width: 24px;
    height: 24px;
    fill: currentColor;  /* inherits text color */
    display: inline-block;
    vertical-align: middle;
  }
  .icon-large { width: 48px; height: 48px; }
</style>

<!-- Color via CSS color (because fill="currentColor") -->
<button style="color: red;">
  <svg class="icon"><use href="#icon-home"/></svg> Home
</button>

外部ファイルからのスプライト

むらのあるのが、(href='file.svg#id' の)外部スプライト参照のブラウザ対応と、CORS の問題です。頑健なアプローチ:スプライトファイルを fetch し、body の上部へインラインの HTML として注入しましょう。HTTP 経由でキャッシュされ、どこでも機能します。これを自動化するのが、(svg-sprite-loader、gulp-svg-sprite の)多くのビルドツールです。

svg
<!-- icons.svg (a separate file) -->
<svg xmlns="http://www.w3.org/2000/svg" style="display:none">
  <symbol id="icon-home" viewBox="0 0 24 24">...</symbol>
</svg>

<!-- Reference external symbols (limited browser support) -->
<svg class="icon"><use href="icons.svg#icon-home"/></svg>

<!-- More reliable: fetch and inject the sprite -->
<script>
  fetch("icons.svg")
    .then(r => r.text())
    .then(text => {
      var div = document.createElement("div");
      div.style.display = "none";
      div.innerHTML = text;
      document.body.insertBefore(div, document.body.firstChild);
    });
</script>

ビルド時のスプライト生成

スプライトの作成を自動化するのが、ビルドツールです。フォルダに個々の .svg ファイルをドロップすれば、適切な <symbol> のラッパー付きでスプライトへ連結するのが、ツールです。人気があるのが、svg-sprite-loader(webpack)、gulp-svg-sprite、vite-plugin-svg です。開発中、アイコンが別々のファイルのまま保たれ、本番のためにバンドルされます。

svg
<!-- Using svg-sprite-loader (webpack) -->
// import all icons in a folder
const req = require.context("./icons", true, /\.svg$/);
req.keys().forEach(req);

// In your component:
<svg class="icon"><use href="#icon-home"/></svg>

<!-- Using gulp-svg-sprite -->
// gulpfile.js
const svgSprite = require("gulp-svg-sprite");
gulp.task("sprite", () =>
  gulp.src("icons/*.svg")
    .pipe(svgSprite({ mode: { symbol: { dest: "." } } }))
    .pipe(gulp.dest("dist"))
);
// Outputs dist/symbol/svg/sprite.symbol.svg

スプライトアイコンのアクセシビリティ

アクセシビリティのためには:純粋に装飾的なアイコン(テキストの隣)には、aria-hidden='true' を印付けしましょう。単独で意味を伝えるなら、<svg> 上に role='img' と aria-label を加えましょう。アイコンのみのボタンには、SVG でなく <button> 上に aria-label を置きましょう。アクセシブルな名前なしで、アイコンだけに頼ってはいけません。

svg
<!-- Decorative icon (hidden from screen readers) -->
<svg class="icon" aria-hidden="true">
  <use href="#icon-decoration"/>
</svg>

<!-- Meaningful icon (with label) -->
<svg class="icon" role="img" aria-label="Home">
  <use href="#icon-home"/>
</svg>

<!-- Icon button with visible text (icon is decorative) -->
<button>
  <svg class="icon" aria-hidden="true"><use href="#icon-home"/></svg>
  <span>Home</span>
</button>

<!-- Icon-only button (needs aria-label on the button) -->
<button aria-label="Search">
  <svg class="icon" aria-hidden="true"><use href="#icon-search"/></svg>
</button>

ツートンとマルチカラーのアイコン

厄介なのが、スプライトでのマルチカラーのアイコンです。<use> の複製が、上書きできるものが限られるためです。ツートンのアイコンのためには、プライマリに currentColor を、セカンダリに固定の色を使いましょう。シンボルの内側の CSS カスタムプロパティ(変数)により、消費者が特定の部分を上書きでき、柔軟なテーマ化のためのモダンな技法が、これです。

svg
<svg style="display:none">
  <!-- Icon with two fill regions -->
  <symbol id="icon-mail" viewBox="0 0 24 24">
    <rect x="2" y="4" width="20" height="16" rx="2" fill="currentColor"/>
    <path d="M2 6 L12 13 L22 6" fill="white"/>
  </symbol>
</svg>

<!-- Override individual parts via CSS (limited: works if the
     symbol uses currentColor and CSS variables) -->
<svg class="icon" style="color: steelblue;">
  <use href="#icon-mail"/>
</svg>

<!-- For full multi-color control, use CSS custom properties -->
<symbol id="icon-alert" viewBox="0 0 24 24">
  <path fill="var(--icon-bg, currentColor)" d="M12 2 L2 22 H22 Z"/>
  <text x="12" y="18" text-anchor="middle" fill="var(--icon-fg, white)">!</text>
</symbol>

<svg class="icon" style="--icon-bg: red; --icon-fg: yellow;">
  <use href="#icon-alert"/>
</svg>
18

SVG の最適化

SVGO の CLI

標準の SVG の最適化器であるのが、SVGO です。メタデータ、コメント、エディタのゴミ(Inkscape/Illustrator の名前空間)、未使用の defs、冗長な属性を取り除き、しばしば 30〜60% のファイルサイズを切り詰めます。すべての本番 SVG 上で実行しましょう。何ができるか見るのが、--show-plugins で、特定の最適化の有効/無効化に、設定ファイルを。

svg
# Install SVGO globally
npm install -g svgo

# Optimize a single file (overwrites)
svgo icon.svg

# Optimize to a new file
svgo icon.svg -o icon.min.svg

# Optimize a folder
svgo -f icons/ -o icons/min/

# Show available plugins
svgo --show-plugins

# Use a specific config
svgo --config=svgo.config.js icon.svg

よくある最適化

SVGO が取り除くもの:XML 宣言、エディタのコメントと名前空間(Adobe、Inkscape)、メタデータ、未使用の xlink、enable-background、xml:space、冗長な fill-rule='nonzero'(デフォルトです)。色値を短縮し(#FF0000 → red)、空白を折りたたみ、パスをマージします。意味的に同一だが、はるかに小さいのが、結果です。

svg
<!-- Before optimization (from Illustrator) -->
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 25.0 -->
<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     xmlns:a="http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/"
     width="100px" height="100px" viewBox="0 0 100 100"
     enable-background="new 0 0 100 100" xml:space="preserve">
  <metadata>...</metadata>
  <path d="..." fill="#FF0000" fill-rule="nonzero"/>
</svg>

<!-- After SVGO -->
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
  <path d="..." fill="red"/>
</svg>

パスの最適化

より短い場合、絶対座標を相対へ変換し、水平/垂直線のための L の代わりに H/V を使い、不必要な小数を取り除き、同一の形状のパスをマージし得るのが、SVGO です。パス文字列の長さをしばしば半分にするのが、これらのパスの最適化です。これを扱うのが、「convertPath」のプラグインで、デフォルトでオンです。

svg
<!-- SVGO can merge and simplify paths -->
<!-- Before: multiple paths with redundant points -->
<g>
  <path d="M 10 10 L 20 10 L 20 20 L 10 20 Z" fill="red"/>
  <path d="M 10 10 L 20 10 L 20 20 L 10 20 Z" fill="none" stroke="black"/>
</g>

<!-- After: merged into one path with combined commands -->
<path d="M10 10h10v10H10z" fill="red" stroke="black"/>

<!-- Path command shortcuts:
     L 20 10  ->  h 10  (relative horizontal)
     L 10 20  ->  v 10  (relative vertical)
     Z closes the path
-->

グループ化と継承

子が継承するよう、共有された属性(fill、stroke、font)を親の <g> へ動かしましょう。これが、ファイルサイズを減らし、一括のスタイルの変更を容易にします。これを自動化するのが、SVGO の「mergePaths」と「moveElemsAttrsToGroup」のプラグインです。SVG を手で書くときは、最初からグループ化しましょう — よりきれいで保守しやすいのです。

svg
<!-- Before: repeated attributes on each element -->
<svg viewBox="0 0 100 100">
  <rect x="10" y="10" width="20" height="20" fill="red" stroke="black" stroke-width="2"/>
  <rect x="40" y="10" width="20" height="20" fill="red" stroke="black" stroke-width="2"/>
  <rect x="70" y="10" width="20" height="20" fill="red" stroke="black" stroke-width="2"/>
</svg>

<!-- After: group with shared attributes -->
<svg viewBox="0 0 100 100">
  <g fill="red" stroke="black" stroke-width="2">
    <rect x="10" y="10" width="20" height="20"/>
    <rect x="40" y="10" width="20" height="20"/>
    <rect x="70" y="10" width="20" height="20"/>
  </g>
</svg>

Gzip と配信

繰り返しの XML のテキストであるため、70〜90% 圧縮されるのが、SVG です。Web サーバーが、gzip か brotli で、image/svg+xml を圧縮することを確保しましょう。配信のためには:レンダリングをブロックするリクエストを避けるため、(折り返し以上の)重要な SVG をインライン化し、(折り返し未満の)イラストには <img loading='lazy'> を。積極的に SVG をキャッシュしましょう — めったに変わらないためです。

svg
<!-- SVG is text, so it gzips very well (70-90% reduction) -->
<!-- Ensure your server sends SVG with gzip/brotli compression: -->

<!-- Apache .htaccess -->
AddType image/svg+xml .svg
<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE image/svg+xml
</IfModule>

<!-- Nginx -->
# gzip_types image/svg+xml;

<!-- HTML: use the right loading strategy -->
<img src="hero.svg" loading="lazy" decoding="async">

<!-- For above-the-fold critical SVG, inline it to avoid a request -->
<!-- For below-the-fold, use <img loading="lazy"> to defer -->

SVGO の設定ファイル

SVGO をカスタマイズするのが、設定ファイルです。よくある調整:viewBox を保つこと(デフォルトでオンの removeViewBox を OFF にすれば、レスポンシブが機能します)、流動的な SVG のための width/height の除去(removeDimensions)、スプライトのための cleanupIDs の有効化(id 名を短縮します)です。最も小さい出力のため、安定するまで最適化を繰り返すのが、multipass です。

svg
// svgo.config.js (SVGO 2+)
module.exports = {
  multipass: true,  // run multiple passes for best result
  js2svg: {
    indent: 2,
    pretty: true,   // readable output (false for minified)
  },
  plugins: [
    { name: "preset-default" },         // sensible defaults
    { name: "removeDimensions", active: true },  // remove width/height (use viewBox)
    { name: "removeViewBox", active: false },    // KEEP viewBox (opposite of default)
    { name: "removeXMLNS", active: false },      // keep xmlns for standalone files
    { name: "cleanupIDs", active: true },        // minify id names
    { name: "mergePaths", active: true },
  ],
};
19

ベストプラクティス

アクセシビリティの要点

アクセシブルな SVG のためには:<title> と <desc> を加え、aria-labelledby 経由で参照し、スクリーンリーダーが画像として SVG を告知するよう role='img' を設定し、IE/Edge のタブストップの問題を防ぐため focusable='false' を加えましょう。aria-hidden='true' であるべきなのが、装飾的な SVG です。支援技術で SVG が使えるのが、これらの実践です。

svg
<!-- 1. Always include <title> and <desc> for meaningful SVGs -->
<svg role="img" aria-labelledby="title-id desc-id">
  <title id="title-id">Annual Revenue Chart</title>
  <desc id="desc-id">A bar chart showing revenue from 2019 to 2023,
    rising from $1M to $5M.</desc>
  <!-- chart content -->
</svg>

<!-- 2. Decorative SVG: hide from screen readers -->
<svg aria-hidden="true" focusable="false">
  <!-- purely visual flourish -->
</svg>

<!-- 3. focusable="false" prevents IE/Edge from making SVG focusable -->
<!-- 4. Use role="img" so screen readers treat SVG as a single image -->

width/height でなく viewBox

viewBox を必ず含めましょう。内部の座標系を定義し、拡縮を可能にします。アイコンのためには、(属性でなく)CSS 経由で width/height を設定し、同じ SVG が任意のサイズで機能するようにしましょう。レスポンシブなグラフィックスのためには、width/height を完全に省き、CSS で width:100%; height:auto を使いましょう。これを強制するのが、SVGO の removeDimensions のプラグインです。

svg
<!-- GOOD: viewBox makes the SVG scalable -->
<svg viewBox="0 0 24 24" style="width: 24px; height: 24px;">
  <path d="..."/>
</svg>

<!-- BAD: fixed width/height limits scalability -->
<svg width="24" height="24">
  <path d="..."/>
</svg>

<!-- For responsive: omit width/height, size with CSS -->
<svg viewBox="0 0 100 100" style="width:100%;height:auto;">
  <circle cx="50" cy="50" r="50"/>
</svg>

テーマ化のための currentColor

アイコンが、周囲のテキストの色を継承するよう、fill='currentColor'(か stroke)を使いましょう。テーマ化が自明になります。親上に color を設定すれば、すべてのアイコンが一致します。CSS の色のトランジション経由で、hover/active の状態も可能になります。意図的に固定でない限り(ブランドのロゴのような)、再利用可能なシンボルでの色のハードコードを避けましょう。

svg
<!-- GOOD: use currentColor so the icon inherits text color -->
<symbol id="icon" viewBox="0 0 24 24">
  <path fill="currentColor" d="..."/>
</symbol>

<!-- Usage: color via CSS -->
<button style="color: tomato;">
  <svg class="icon"><use href="#icon"/></svg> Themed
</button>

<button style="color: steelblue;">
  <svg class="icon"><use href="#icon"/></svg> Also themed
</button>

<!-- BAD: hardcoded colors can't be themed -->
<symbol id="icon">
  <path fill="#333333" d="..."/>  <!-- always gray -->
</symbol>

セマンティックなグループ化

(背景、軸、データ、ラベルの)論理的なロールにより、形状のタイプだけでなく、意味のある id 付きで要素をグループ化しましょう。これで、SVG が維持、スタイル、スクリプトしやすくなり、グループ全体を表示/非表示や再スタイルできます。アクセシビリティ(グループ上の aria-labelledby)とデバッグにも役立ちます。

svg
<svg viewBox="0 0 200 200">
  <!-- Group by logical component, not just by shape type -->
  <g id="background">
    <rect width="200" height="200" fill="#f0f0f0"/>
  </g>
  <g id="chart-axis">
    <line x1="20" y1="180" x2="180" y2="180" stroke="black"/>
    <line x1="20" y1="20" x2="20" y2="180" stroke="black"/>
  </g>
  <g id="chart-data" fill="steelblue">
    <rect x="30" y="100" width="20" height="80"/>
    <rect x="60" y="60" width="20" height="120"/>
    <rect x="90" y="80" width="20" height="100"/>
  </g>
  <g id="labels" font-size="10" fill="black">
    <text x="40" y="195" text-anchor="middle">Q1</text>
    <text x="70" y="195" text-anchor="middle">Q2</text>
  </g>
</svg>

過剰描画と複雑さの回避

(完全に覆われた形状の描画である)過剰描画が、レンダリング時間を浪費するため、隠れた要素を取り除きましょう。パスを単純化しましょう:数百の小さい線分の代わりに、C/Q の曲線を使い、小数の精度を減らす(10.499999 → 10.5)のです。複雑なイラストのためには、ラスタ画像がより小さく速いかどうか検討しましょう。ブラウザのペイントプロファイラでプロファイルしましょう。

svg
<!-- BAD: layered shapes that cover each other (overdraw) -->
<g>
  <rect width="100" height="100" fill="red"/>
  <rect width="100" height="100" fill="blue"/>  <!-- covers red -->
  <rect width="100" height="100" fill="green"/> <!-- covers blue -->
</g>
<!-- The red and blue are never visible but still rendered -->

<!-- GOOD: only draw what's visible -->
<rect width="100" height="100" fill="green"/>

<!-- BAD: path with 10,000 points for a simple shape -->
<path d="..."/>  <!-- over-tessellated -->

<!-- GOOD: simplify paths; use curves instead of many line segments -->
<path d="M 10 50 Q 50 10, 90 50"/>  <!-- one curve vs 100 lines -->

テストと検証

どのコードのように SVG をテストしましょう:XML の検証、クロスブラウザの描画の確認(一部のフィルタでの Safari の癖があります)、様々なサイズでのテスト(500px のヒーロー対 16px のアイコン)、スクリーンリーダーの出力の検証、ファイルサイズの確認(アイコンは 2KB 未満であるべき)です。最適化されていない SVG の ship を防ぐため、CI で SVGO を実行しましょう。少しのテストが、本番の驚きを防ぎます。

svg
<!-- 1. Validate SVG XML -->
<!-- Use the W3C validator: https://validator.w3.org/ -->

<!-- 2. Test in multiple browsers -->
<!-- Chrome, Firefox, Safari, Edge, (IE if required) -->

<!-- 3. Test at different sizes -->
<div style="width: 16px;"><svg>...</svg></div>  <!-- icon -->
<div style="width: 500px;"><svg>...</svg></div> <!-- hero -->

<!-- 4. Test with screen readers (VoiceOver, NVDA) -->

<!-- 5. Check file size after optimization -->
ls -la icon.svg  # should be under 2KB for simple icons

<!-- 6. Verify currentColor theming works -->
<!-- 7. Ensure no hardcoded dimensions block responsiveness -->

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.