如何更改SVG元素的曲线

时间:2015-11-24 16:21:31

标签: javascript d3.js svg

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

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
}

但我似乎无法弄清楚如何改变曲线:(

1 个答案:

答案 0 :(得分:2)

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



<!DOCTYPE html>
<html>

  <head>
    <script data-require="d3@3.5.3" 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>
&#13;
&#13;
&#13;