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

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

 メニュー

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

【SVG】要素の追加と削除

要素の追加と削除について書きます。サンプルとして、円の追加と削除の例を見ていきます。具体的な書き方は、サンプルコードを確認してください。

要素オブジェクトの生成と追加

要素の追加の流れは以下の通りです。

  1. 要素を生成する
  2. 要素を任意の要素に追加する
document.createElementNS(名前空間名, "要素名");
追加される要素の要素名.appendChild(生成した要素名);

要素を生成しただけでは属性が設定されていないので、setAttributeNS()で適宜属性を設定する。

デモ

図形をクリックするとcircle要素が追加される例。

<g fill="cyan" onclick="appendCircle()">
  <rect x="10" y="55" width="40" height="20"/>
  <text x="10" y="90" font-size="12">円を生成</text>
</g>
<script type="text/javascript">

let SVG = "http://www.w3.org/2000/svg";
let rootobj = document.documentElement;  //ルート要素

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

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

function appendCircle() {
  let circle = document.createElementNS(SVG, "circle");
  circle.setAttributeNS(null, "cx", randomInt(100));
  circle.setAttributeNS(null, "cy", randomInt(45));
  circle.setAttributeNS(null, "r", randomInt(8)+2);
  circle.setAttributeNS(null, "fill", randomColor());
  rootobj.appendChild(circle);  //ルート要素に追加
}
</script>

円を生成

要素の削除

削除する要素の親要素.removeChild(削除する要素名);

デモ

クリックすると要素が削除される。

<script type="text/javascript">//<![CDATA[
let SVG = "http://www.w3.org/2000/svg";
let demo2 = document.getElementById('demo2');
initialize();
function removeRect(evt) {
  demo2.removeChild(evt.target);
}
function appendCRect(x, y, w, h, rx, fill, onclick) {
  let rect = document.createElementNS(SVG, "rect");
  rect.setAttributeNS(null, "x", x);
  rect.setAttributeNS(null, "y", y);
  rect.setAttributeNS(null, "width", w);
  rect.setAttributeNS(null, "height", h);
  rect.setAttributeNS(null, "rx", rx);
  rect.setAttributeNS(null, "fill", fill);
  rect.setAttributeNS(null, "onclick", onclick);
  demo2.appendChild(rect);
}
function initialize() {
  for(let x = 10; x<= 90; x += 10){
    for(let y = 10; y <= 60; y += 10){
      appendCRect(x, y, 10, 10, 5, "magenta",  "removeRect(evt)");
    }
  }
}
//]]>
</script>

補足:CDATAセクション

<script type="text/javascript"><![CDATA[

  //コードの中身

]]></script>

コードを囲っている<![CDATA[]]>をCDATAセクションと言う。SVGXMLの一種で<などの特殊な文字を扱う場合は、CDATAセクションで囲う。<>などの特殊な文字をコード内で使えるようするため、CDATAセクションで囲っている。

まとめ

要素の追加と削除について書きました。要素を追加するには、まず要素を生成する必要があります。生成して初めて追加できます。

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