我有这个功能来创建两点之间的曲线

var amountOfCurve = (d.noOfSameConnections+1); //between 0 and 10
        var dy = d.target.x - d.source.x,
        dx = d.target.y - d.source.y,
        dr = Math.sqrt(dx * dx + dy * dy) *(amountOfCurve);

        return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + (d.target.x) + "," + (d.target.y);


某些链接具有相同的源和目标。我在noOfSameConnections中解决了这个问题。但是我想要的是替代不同大小的曲线,因为两个节点之间最多只能有两个链接,我希望链接以另一种方式弯曲。所以我会做这样的事情:

if(d.noOfSameConnections === 1){
//curve one way
} else {
//curve the other
}


但是我似乎无法弄清楚如何在:(

最佳答案

弧的方向可以用sweep flag控制。



<!DOCTYPE html>
<html>

  <head>
    <script data-require="[email protected]" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
  </head>

  <body>
    <script>

      var svg = d3.select('body')
        .append('svg')
        .attr('width', 500)
        .attr('height', 500);

      var d = {
        source: {
          x: 10,
          y: 10
        },
        target: {
          x: 490,
          y: 490
        }
      };

     var dy = d.target.x - d.source.x,
         dx = d.target.y - d.source.y,
         dr = Math.sqrt(dx * dx + dy * dy) * 0.8;

      var largeSweep = 0;
      var sweep = 1;

      svg.append("path")
        .attr("d", "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 " + largeSweep + "," + sweep + " " + d.target.x + "," + d.target.y)
        .style("fill", "none")
        .style("stroke", "steelblue")
        .style("stoke-width", 2);

      largeSweep = 0;
      sweep = 0;

      svg.append("path")
        .attr("d", "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 " + largeSweep + "," + sweep + " " + d.target.x + "," + d.target.y)
        .style("fill", "none")
        .style("stroke", "orange")
        .style("stoke-width", 2);

    </script>
  </body>

</html>

关于javascript - 如何更改SVG元素上的曲线,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33898739/

10-13 03:09