d3.js Bottom to Top force layout - drag behavior

944 views Asked by At

I've a bottom to top force tree layout. Somehow the drag behavior doesn't work as per expectation out of the box obviously. I'm not able to find a perfect way to achieve the desired drag behavior. As one can observe, it is currently in inverse direction to the tree.

Block - http://bl.ocks.org/git-ashish/6d5f8014661488ae786b

fiddle - http://jsfiddle.net/ashishsingh/jyrwsa0y/

function tick(e) {

// Push sources up and targets down to form a weak tree.
var k = 6 * e.alpha;
json.links.forEach(function(d, i) {
  d.source.y -= k;
  d.target.y += k;
});

node.attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return h - d.y; });

link.attr("x1", function(d) { return d.source.x; })
    .attr("y1", function(d) { return h - d.source.y; })
    .attr("x2", function(d) { return d.target.x; })
    .attr("y2", function(d) { return h - d.target.y; });
}

Any help or directions would be appreciated.

Thanks.

1

There are 1 answers

1
LeartS On BEST ANSWER

I don't know what you mean in the comment with "weak tree", but it seems to me like you want to put source down and targets up, not viceversa.

Changing the tick function with this:

function tick(e) {

var k = 6 * e.alpha;
json.links.forEach(function(d, i) {
  d.source.y += k;
  d.target.y -= k;
});

node.attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; });

link.attr("x1", function(d) { return d.source.x; })
    .attr("y1", function(d) { return d.source.y; })
    .attr("x2", function(d) { return d.target.x; })
    .attr("y2", function(d) { return d.target.y; });
}

You get this behaviour (fiddle) which is the top-down inverted equivalent of this example, which seems to be what you want.