SVG入門

トップ > SVG入門

目次

SVGとは

Web でよく使用される SVG 画像フォーマットについて説明します。

本ページでは、SVG のごく一部の機能のみを説明しますので、詳細は下記の仕様書や他のリファレンスを参照してください。

仕様書

SVGの書き方

画像ファイルとして

SVG は通常の画像ファイルとして、<img>background-image などで読み込むことができます。

svg-sample.svg
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg">
  <rect x="0" y="0" width="100" height="60" fill="#ddd" />
  <polygon points="50 10, 70 30, 50 50, 30 30" fill="#99f" />
</svg>
HTML
<img src="svg-sample.svg" width=100 height=60>   // 非圧縮の場合

もしくは、上記の *.svg ファイルを gzip 圧縮し、拡張子を *.svgz に変更したものを読み込むこともできます。

HTML
<img src="svg-sample.svgz" width=100 height=60>  // gzip 圧縮の場合
表示
SVG Image
HTML要素として

下記の様に HTML 中に直接記述することもできます。

HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>SVG Test</title>
</head>
<body>
<svg x=0 y=0 width=100 height=60 style="background-color: #ddd">
  <polygon points="50 10, 70 30, 50 50, 30 30" fill="#99f" />
</svg>
</body>
</html>

描画

<line x1= y1= x2= y2= ...>

直線を描画します。x1(開始点のX座標)、y1(開始点のY座標)、x2(終了点のX座標)、y2(終了点のY座標) などを指定します。

SVG
<line x1="10" y1="30" x2="190" y2="30" stroke="black" stroke-width="2" />
表示
<rect x= y= width= height= ...>

矩形を描画します。x(左上のX)、y(左上のY)、width(横幅)、height(高さ) などを指定します。

SVG
<rect x="5" y="5" width="30" height="30" stroke="black" fill="#fff" stroke-width="2" />
表示
<polygon points= ...>

多角形を描画します。posts には、x1 y1, x2 y2, x3 y3, ... のように軌跡点を指定します。軌跡の最後は開始点に向けて閉じます。

SVG
<polygon points="5 20, 20 5, 35 20, 20 35" stroke="black" fill="#fff" stroke-width="2" />
表示
<circle cx= cy= r= ...>

円を描画します。cx(中心点のX)、cy(中心点のY)、r(半径) などを指定します。

SVG
<circle cx="20" cy="20" r="15" stroke="black" fill="#fff" stroke-width="2" />
表示
<ellipse cx= cy= rx= ry= ...>

楕円を描画します。cx(中心点のX)、cy(中心点のY)、rx(X軸方向の半径)、ry(Y軸方向の半径) などを指定します。

SVG
<ellipse cx="20" cy="20" rx="15" ry="8" stroke="black" fill="#fff" stroke-width="2" />
表示
<path d= ...>

パスを描画します。d には、パス描画の命令を記述します。M 5 20 は、x=5, y=20 に移動せよ(Move to)、L 20 5 は x=20 y=5 に線を引け(Line to) を意味します。

SVG
<path d="M 5 20 L 20 5 L 35 20 L 20 20" stroke="black" fill="transparent" stroke-width="2" />
表示
二次ベジェ曲線
(Start) (x, y) (x1, y1)
三次ベジェ曲線
(Start) (x, y) (x1, y1) (x2, y2)

アニメーション

<animate ...>

アニメーションを行います。attributeName で指定した属性を、from から to の値まで、dur で指定した時間で変動させます。repeatCount には回数を指定します。

SVG
<svg x="0px" y="0px" width="400px" height="40px" style="background-color:#ddd">
  <rect x="5" y="5" width="30" height="30" stroke="black" fill="#fff" stroke-width="2">
    <animate attributeName="x" from="-30" to="400" dur="4s" repeatCount="indefinite" />
  </rect>
</svg>
表示

その他

リンクを張ります。HTML の <a> と同様、クリックするとその URL にジャンプします。

SVG
<svg x="0px" y="0px" width="400px" height="60px" style="background-color:#ddd">
  <a xlink:href="http://www.yahoo.co.jp">
    <polygon id="logomark-polyline" fill-rule="evenodd" clip-rule="evenodd"
      fill="#99f" points="200 10, 220 30, 200 50, 180 30"/>
  </a>
</svg>
表示

Copyright (C) 2018 杜甫々
初版:2018年1月28日 最終更新:2018年1月28日
http://www.tohoho-web.com/ex/svg.html