How to clone an element or dom piece?

I am trying to create a beautiful tree with D3.

And for the nodes, I have an SVG template in a hidden div. But I tried to "clone" the "template" with many D3 functions, but everything did not work.

Latest javascript code:

...
var node = svg.selectAll("g.node")
            .data(nodes)
            .enter()
            .append("svg:g")
            .attr("transform",
                    function(d)
                    {
                        return "translate(" + d.y + "," + d.x + ")";
                    }
            );

var template_box = d3.select("#layer1");
console.log(template_box);

node.insert(template_box);
...

A html patch:

...
    <body>
 <svg width="400" height="400">
 <g
 id="layer1"
 transform="translate(-208.375,-410.5)">
<rect
...

Sincerely.

+2
source share
1 answer

If you try to identify some shapes in front and then reuse them in different positions of the chart, you will get better results with svg <defs>and <use>. See this simple background example . You can create your form in front like this:

<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="400" height="400">
 <defs>
   <g id="layer1" transform="translate(-208.375,-410.5)">
     <rect
     ...

, <g>, definition. , :

var node = svg.selectAll("g.node")
  .data(nodes)
  .enter()
  .append("g")
  .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; } )

node.append("use")
  .attr("xlink:href","#layer1")

, xlink svg .

UPDATE: :

http://bl.ocks.org/explunit/5988971

+4

Source: https://habr.com/ru/post/1546405/


All Articles