基于力的布局中的自定义节点排斥

时间:2014-07-15 17:51:18

标签: d3.js force-layout

有没有办法让d3了解我想要应用到基于力的图的某些节点的自定义力?例如,在这个小提琴中:JSFiddle我创建了3个节点,我希望将其分组为一个矩形,另外一个节点应该在该组之外,除非它没有因为D3没有办法知道。

以下是允许我定位节点和组的代码:

function positionAll() {
    positionGroups(d3.selectAll('.myrect'));
}

function positionGroups(data) {
    var groupBoundaries=[];
    data.each(function(d,i) {
        var boundaries = positionRect.call(this,d);
        if (d.group !== undefined) {
            if (!groupBoundaries[d.group]) {
                groupBoundaries[d.group]=[];
            }
            groupBoundaries[d.group].push(boundaries);
        }
    });

    d3.forEach(groupBoundaries, function(boundaries, currentGroup) {
        var topBoundary =    d3.min(boundaries, function(coord) { return coord.y1; }) - 10;
        var rightBoundary =  d3.max(boundaries, function(coord) { return coord.x2; }) + 10;
        var bottomBoundary = d3.max(boundaries, function(coord) { return coord.y2; }) + 10;
        var leftBoundary =   d3.min(boundaries, function(coord) { return coord.x1; }) - 10;

        d3.select('.group').filter(function(group) { return group.name === currentGroup; })
            .attr("x",leftBoundary)
            .attr("y",topBoundary)
            .attr("width",rightBoundary-leftBoundary)
            .attr("height",bottomBoundary-topBoundary);
    });
};

function positionRect(d) {
    var x = d.x || 0;
    var y = d.y || 0;

    d3.select(this)
        .attr("x", x)
        .attr("y", y);

    return {x1: x, y1: y, x2: x+this.getBBox().width, y2: y+this.getBBox().height};
};

当然我可以手动计算出组外节点的位置,但是我不会真正利用力布局。

0 个答案:

没有答案