Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3, retrieve the x position of a <g> element and apply multiple transform

With D3.js I want to transform the x of a group many times (eg. by clicking a button a causing a transform for every click), starting from the current position of the group. Problem is I can't retrieve the x of the group and, even if I find it, I can't find any built-in function that lets me change the x of a group starting from its current x. Am I missing something important? It's very strange I can't get the x of an element added to an SVG "stage".

My code is the following (edited for Lars): I created the nodes the way you suggested me yesterday (cloning them).

var m=[5,10,15,20,25,30];

var count=0;

d3.select('svg').on("mouseup", function(d, i){

     count+=0.5;

     var n = d3.selectAll(".myGroup");

     n.each(function(d,i) {

        if(i!=0){
            // here I need to know the current x of the current n element but I 
            // can't get it
            // this causes error "Uncaught TypeError: undefined is not a function"
            // var currentx = d3.transform(this.attr("transform")).translate[0];

            this.setAttribute("transform", "translate("+((100/m[i])*count)+",10)");

        }

     });

});
like image 220
Steekatsee Avatar asked Apr 24 '14 17:04

Steekatsee


1 Answers

Getting and changing the position of a g element is relatively straightforward. For example like this:

var g = d3.select("#myG");

// get x position
var currentx = d3.transform(g.attr("transform")).translate[0];

// set x position
g.attr("transform", "translate(" + (currentx + 100) + ",0)");

Edit:

If you have a raw DOM element, select it with D3 first:

var currentx = d3.transform(d3.select(this).attr("transform")).translate[0];
like image 98
Lars Kotthoff Avatar answered Nov 13 '22 09:11

Lars Kotthoff