【问题标题】:d3 force layout link position in noded3 在节点中强制布局链接位置
【发布时间】:2014-08-01 12:37:57
【问题描述】:

我已经阅读了几个关于 d3 force layout 的问题,但我还没有找到答案,所以我发布了这个。

我正在使用 D3 库,特别是力布局。我没有向节点添加预定义的形状,而是创建自己的形状,如圆形、矩形等。

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);

可以查看完整代码here

我不明白如何更改图表的链接(或边)进入每个节点的位置。

例如:我希望从矩形节点出来的边缘位于矩形的中心,而不是左上角(我猜是位置 0,0)。 我现在肯定有一些与 SVG 中每个形状的 CX 和 CY 相关的东西,但这超出了我的掌握。

我希望我的问题很清楚,请随时提出我可能遗漏的任何问题

谢谢!

【问题讨论】:

  • 可以设置数据项的x和y属性来设置初始位置。

标签: javascript svg d3.js force-layout


【解决方案1】:

只需将形状的中心作为原点,而不是将矩形定义为

   rect : "M 0 0 L 0 "+ rect_size + "L "+ 2 * rect_size + " "+ rect_size + " L "+ 2 * rect_size + " 0 L 0 0",

定义为

   rect : "M " + -rect_size + " " + (-rect_size / 2) + " h " + 2 * rect_size + " v " + rect_size + " h "+ (-2 * rect_size) + " z",

我已经从 L 换成了 h、v 和 z,所以它更简单。你可以对其他形状做同样的事情。

【讨论】:

    猜你喜欢
    • 2018-02-05
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 2014-11-23
    • 2014-11-20
    • 1970-01-01
    相关资源
    最近更新 更多