Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

duplicating the whole svg element using d3.js

I am creating a rectangle using d3.js, inside that rectangle i am creating 10 smaller rectangles`.

i want to replicate whole thing into another svg element on mouse click.

jsfiddle link of the code : http://jsfiddle.net/nikunj2512/XK585/

Here is the code:

var svgContainer = d3.select("body").append("svg")
.attr("width", 200)
.attr("height", 200);

//Draw the Rectangle
var rectangle = svgContainer.append("rect")
.attr("x", 10)
.attr("y", 10)
.attr("fill", "red")
.attr("width", 200)
.attr("height", 200);

var bigRectContainer = d3.select('#bigRectContainer').append('svg')
    .attr('width', 200)
    .attr('height', 200);
var dim = 20;
var x = 0;
var y = 0;
for (i = 1; i < 11; i++) {

    x = 10 + (i-1)*dim;
    //alert(x);
y = 10;

    svgContainer.append("rect")
        .attr("x", x)
        .attr("y", y)
        .attr("width", 20)
        .attr("height", 20)
        .style("fill", "black");
 }

 var bigRectContainer = svgContainer.append("g");
 svgContainer.selectAll("rect").on("click", function () {
 var littleRect = d3.select(this);
console.log(littleRect)

var bigRect = bigRectContainer.selectAll("rect")
                       .data(littleRect)
                       .enter()
                       .append("rect");

 });

Please tell me where i made the mistake...

like image 836
Nikunj Aggarwal Avatar asked Dec 28 '25 16:12

Nikunj Aggarwal


1 Answers

I'm not entirely certain what you're trying to do with the code you've posted, but I thought that duplicating an entire SVG node was interesting. It turns out it's quite easy to do with selection#html - this doesn't work on the SVG node, but it does work on its container, so it's easy to clone the whole node:

function addAnother() {
    var content = d3.select(this.parentNode).html();
    var div = d3.select('body').append('div')
        .html(content);
    div.selectAll('svg').on('click', addAnother);
}

svg.on('click', addAnother);

See working fiddle here. Note that this only works if the SVG node is the only child of its parent - otherwise, you might need to wrap it somehow.

like image 138
nrabinowitz Avatar answered Dec 31 '25 05:12

nrabinowitz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!