Reputation: 175
I've been reading several questions about d3 force layout, but I haven't found my answer yet, so I'm posting this.
I'm working with the D3 library, specifically with the force layout. Instead of adding pre-defined shapes to the nodes, I'm creating my own shapes like circles, rects and so on.
var shapes = {
star : "m 0 0 l 23 12 l -4 -26 l 19 -19 l -27 -4 l -11 -23 l -12 23 l -27 4 l 19 19 l -4 26 l 24 -12",
rect : "M 0 0 L 0 "+ rect_size + "L "+ 2 * rect_size + " "+ rect_size + " L "+ 2 * rect_size + " 0 L 0 0",
vertical_rect : "M 0 0 L 0 "+ 2 * rect_size + "L "+ rect_size + " "+ 2 * rect_size + " L "+ rect_size + " 0 L 0 0",
circle: "M 0 0 A "+ radius + " " + radius +" 0 1 0 0.00001 0 Z"
};
var dummy_nodes = {};
var dummy_shapes = {"A" : shapes.circle, "B" : shapes.rect, "C" : shapes.rect, "D" : shapes.circle};
// Compute the distinct nodes from the links.
links.forEach(function (link) {
link.source = dummy_nodes[link.source] || (dummy_nodes[link.source] =
{ name: link.source, shape: dummy_shapes[link.source]});
link.target = dummy_nodes[link.target] || (dummy_nodes[link.target] =
{ name: link.target,shape: dummy_shapes[link.target]});
});
var force = d3.layout.force()
.nodes(d3.values(dummy_nodes))
.links(links)
.size([960, 500])
.linkDistance(200)
.charge(-1500)
.on("tick", tick)
.start();
var svg = d3.select("body").append("svg:svg")
.attr("width", w)
.attr("height", h);
var node = svg.append("svg:g").selectAll(".node")
.data(force.nodes())
.enter().append("path")
.attr("class", "node")
.attr("d", function(n){ return n.shape})
.on("dblclick", dblclick)
.call(drag);
You can view the entire code here
I don't understand how I can change the position in wich the links(or edges) of the graph enter each node.
For example: I would like that the edges coming out of the rectangle nodes where positioned in the center of the rect, instead of the top left corner( I guess is position 0,0). I now there must be something related with the CX and CY of each shape from SVG, but it's beyond my grasp.
I hope that my question is clear, feel free to ask anything that I've might left out
Thanks!
Upvotes: 2
Views: 1131
Reputation: 124249
Just make the centre of your shape the origin i.e. instead of defining a rect as
rect : "M 0 0 L 0 "+ rect_size + "L "+ 2 * rect_size + " "+ rect_size + " L "+ 2 * rect_size + " 0 L 0 0",
define it as
rect : "M " + -rect_size + " " + (-rect_size / 2) + " h " + 2 * rect_size + " v " + rect_size + " h "+ (-2 * rect_size) + " z",
I've swapped from L to h, v and z so it's simpler. You can do the same thing with the other shapes.
Upvotes: 1