SVGで文字を表示するにはtext要素を使います。<text>とと</text>の
間に表示する文字列を書きます。ただ、このままでは文字は表示
されません。文字を表示するには、文字の色(又はは線の色)を指定
しなかればなりません。
サンプルコードの実行結果はこちら
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 |
<!DOCTYPE html> <head> <meta charset="utf-8"> <title>文字をを描画する</title> <style> svg{min-height:60px;} </style> <script src="../js/d3.js"></script> </head> <body> <h1>文字列を表示する</h1> <svg> <text x="32" y="32" style="fill:black;">SVGテキスト</text> </svg> <h1>文字サイズを32px、太字と指定する</h1> <svg> <text x="32" y="32" font-size="32px" font-weight="bold">SVGテキスト</text> </svg> <h1>文字の表示基準位置を指定する</h1> <svg style="min-width:400px;"> <rect x="200" y="0" width="2" height="120" style="fill:green;" /> <text x="200" y="20" style="fill:black;" text-anchor="start">text-anchor="start"</text> <text x="200" y="60" style="fill:black;" text-anchor="middle">text-anchor="middle"</text> <text x="200" y="100" style="fill:black;" text-anchor="end">text-anchor="end"</text> </svg> <script src="test.js"></script> </body> </html> |
フォントや文字の大きさ、太さを指定する
text要素には、書体やサイズを指定することができます。
主なものは下記の通りです。値・内容はCSSと同じです。
属性 | 説明 |
---|---|
font-family | 書体 |
font-size | 文字サイズ |
font-weight | 太字の太さ |
文字の表示基準位置を変更する
text要素には文字の表示基準位置を指定するtext-anchor属性があります。
これは文字の左揃え、中央、右揃えを指定するものです。
text-anchorの属性値は下記の通りです。
属性値 | 説明 |
---|---|
start | 左揃え |
middle | 中央 |
end | 右揃え |