d3动态曲线的力布局

时间:2013-07-09 13:59:16

标签: javascript d3.js force-layout bezier

我想在力布局中使用动态贝塞尔曲线,如cytoscape example,在d3中是否可以?看到这个d3 example但是使用arc。 我不知道算法,有人有想法吗?

1 个答案:

答案 0 :(得分:2)

我看到了cytoscape库,并且这个algorytm有效

function tick() {
     path.attr("d", function (d) {
          var coordinatesP = findEdgeControlPoints(d);
          return "M" + d.source.x + "," + d.source.y + "S" + coordinatesP.xp + "," + coordinatesP.yp + " " + d.target.x + "," + d.target.y;
     });
     hashTable = {};
          nodes.attr("cx", function (d) { return d.x; })
               .attr("cy", function (d) { return d.y; });
}

var findEdgeControlPoints = function (d) {
        var midPointX = (d.source.x + d.target.x) / 2;
        var midPointY = (d.source.y + d.target.y) / 2;

        var displacementX, displacementY;

        displacementX = d.target.y - d.source.y;
        displacementY = d.source.x - d.target.x;

        var displacementLength = Math.sqrt(displacementX * displacementX + displacementY * displacementY);

        displacementX /= displacementLength;
        displacementY /= displacementLength;

        var distanceFromMidpoint = findPathDeltaControlPoint(d);


        var xp = midPointX + displacementX * distanceFromMidpoint;
        var yp = midPointY + displacementY * distanceFromMidpoint;

        return {xp : xp, yp : yp};

    };
    var findPathDeltaControlPoint = function (edge) {
        /*caso statico il primo al centro e tutti gli altri ai lati*/
        /*conto le occorrenze */
        var pairId,
            delta,
            TICK = 20;
        pairId = edge.source.id > edge.target.id ?
                edge.target.id + '-' + edge.source.id :
                edge.source.id + '-' + edge.target.id;

        if (hashTable[pairId] == undefined) {
            hashTable[pairId] = [];
        }
        if (edge[pairId] == undefined) {
            edge[pairId] = [];
        }
        if (edge[pairId].length == 0) {
            edge[pairId].push(pairId);
        }
        hashTable[pairId].push(edge);
        // Ceck if is the first occurence
        var pairIdOccurence = hashTable[pairId].length;
        if (pairIdOccurence == 1) {
            delta = 0;
        } else if (pairIdOccurence > 1) {
            // Check if is equal
            if (pairIdOccurence % 2 == 0) {
                delta = (TICK * pairIdOccurence) / 2;
            } else {
                delta = -((TICK * (pairIdOccurence - 1)) / 2);
            }
        }
        return delta;
    };