複数のSVG用をまとめて扱う場合に必要なものはグループ化です。
SVGではg要素を使って要素を囲みます。グループ化すると要素の
スタイルや位置を纏めて扱うことができます。g要素のスタイルは
内包する要素にも継承されます。
サンプルコードの実行結果はこちら
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<!DOCTYPE html> <head> <meta charset="utf-8"> <title>図形の移動とグループ化</title> <style> svg{min-height:220px;} </style> </head> <body> <h2>図形のグループ化</h2> <svg> <g style="opacity:0.3;"> <rect x="100" y="45" width="100" height="80" /> <text x="100" y="40" text-anchor="start" style="fill:black;">GROUP TEST</text> </g> </svg> <h2>図形のグループ化とまとめて位置調整</h2> <svg> <g transform="translate(-50,-20)"> <rect x="100" y="45" width="100" height="80" /> <text x="100" y="40" text-anchor="start" style="fill:black;">GROUP TEST</text> </g> </svg> <h2>図形を回転</h2> <svg> <g transform="rotate(30,150,0)"> <rect x="200" y="45" width="100" height="80" /> <text x="200" y="40" text-anchor="start" style="fill:black;">GROUP TEST</text> </g> </svg> <h2>図形を拡大 1.5倍</h2> <svg> <g transform="scale(1.5)"> <rect x="100" y="45" width="100" height="80" /> <text x="100" y="40" text-anchor="start" style="fill:black;">GROUP TEST</text> </g> </svg> </body> </html> |
まとめて位置を調整する
g要素によりグループ化するメリットは、スタイルの指定よりも、
纏めて位置を調整できることです。D3.jsでは目盛りを表示することが
多いので、目盛りの線とラベルをグループ化して位置を調整することが
あります。
位置を調整する場合、g要素にtransform属性を指定します。
transform属性に下記の機能を指定できます。
機能 | 説明 |
---|---|
translate(tx,ty) | 相対的に位置を移動。例:横方向に20px、縦方向にー50px移動→translate(20px,-50px) |
scale(s),scale(sx,sy) | 拡大・縮小 例:横3倍、縦5倍→scale(3,5) |
rotate(d),rotate(d,cx,cy) | 回転。例反時計回りに60度回転→rotate(-60) |