5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

D3.jsで要素をコピーして追加する

Last updated at Posted at 2016-02-18

z-indexが効かないsvgでは、特定の要素を最前面に出したいときなどに要素をコピーして他の要素よりあとに追加するなどの処理が頻繁に必要になる。

サンプル

「circle要素を属性値丸ごとコピーしたい」ってときは以下の方法でコピーできる。

html
<svg>
  <circle cx="100" cy="60" r="40" fill="red" stroke="black" />
  <circle cx="300" cy="120" r="60" fill="blue" stroke="black" /> 
</svg>
javascript
var svg = d3.select("svg")

d3.selectAll("circle") //コピーする対象をセレクト
  .each(copy);

function copy(){
  var nodeName = d3.select(this).node().nodeName;
  var nodeAttr = d3.select(this).node().attributes;

  var objAttr = {}
  Object.keys(nodeAttr).forEach(function(key){
    objAttr[nodeAttr[key].name] = nodeAttr[key].value;
  });

  svg.append(nodeName).attr(objAttr); //コピーした要素を追加する
}

5
3
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?