元Webデザイナー兼コーダーの備忘録

ウェブデザインやプログラミング、ブログのカスタマイズなどについてアウトプットしています。

 メニュー

» HTML入門のまとめはこちらです。

【SVG】テキスト要素の生成と追加

テキスト要素の生成と追加について書きます。具体的な書き方は、サンプルコードを確認してください。

テキストオブジェクトの生成

document.createTextNode("テキスト");

テキストオブジェクトの追加の流れは以下の通りです。

  1. テキスト要素を生成する
  2. テキストを生成する
  3. テキスト要素にテキストを追加する
  4. テキストを持つテキスト要素を任意の要素に追加する

デモ

図形をクリックするとテキストがランダムに追加される。

<g fill="cyan" onclick="appendText()">
  <rect x="10" y="55" width="40" height="10"/>
  <text x="10" y="80" font-size="12">テキストを生成</text>
</g>

<script type="text/javascript">

var SVG = "http://www.w3.org/2000/svg";
var rootobj = document.documentElement;

function randomInt(range) {
  return Math.floor(Math.random()*range);
}

function randomChar() {
  return String.fromCharCode(randomInt(93)+33);
}

function randomColor() {
  return `rgb(${randomInt(255)},${randomInt(255)},${randomInt(255)})`;
}

function appendText() {
  var textobj = document.createTextNode(randomChar());
  var textele = document.createElementNS(SVG, "text");
  textele.appendChild(textobj);
  textele.setAttributeNS(null, "x", randomInt(100));
  textele.setAttributeNS(null, "y", randomInt(50));
  textele.setAttributeNS(null, "font-family", "serif");
  textele.setAttributeNS(null, "font-size", randomInt(32)+8);
  textele.setAttributeNS(null, "fill", randomColor());
  rootobj.appendChild(textele);
}
</script>

テキストを生成

まとめ

テキスト要素の生成と追加について書きました。テキスト要素にテキストを追加してから任意の要素にテキスト要素を追加します。

» HTML入門のまとめはこちらです。