节点末尾的箭头链接d3.js

时间:2019-06-14 11:46:23

标签: javascript angular d3.js

我正在构建一棵树,并且已经做了一些结构:enter image description here

我的链接代码如下:

   const links = d3
        .select('svg g.links')
        .selectAll('line.link')
        .data(root.links())
        .enter();

    links
        .append('path')
        .classed('link', true)
        .attr('d', this.buildCurvedNodesJointLine);

    buildCurvedNodesJointLine(d) {
     if (d.target.data.noParent) {
         return 'M0,0L0,0';
     }

     const ny = d.target.y + (d.source.y - d.target.y) * 0.5;

     const linedata: any = [
         {
            x: d.target.x,
            y: d.target.y
         },
         {
            x: d.target.x,
            y: ny
         },
         {
            x: d.source.x,
            y: d.source.y
         }
     ];

     const fun = d3
        .line()
        .x((data1: any) => data1.x)
        .y((data2: any) => data2.y)
        .curve(d3.curveStepAfter);

     return fun(linedata);

buildCurvedNodesJointLine函数为我的节点构建弯曲的链接。 但是我不能在链接行的末尾添加方向箭头。所以看起来可能像这样: enter image description here

1 个答案:

答案 0 :(得分:0)

看看marker-end属性,该属性将自动附加已定义的标记,并且在标记的orient属性设置为auto的情况下,也可以以正确的方式进行定位。

<!DOCTYPE html>

<head>
  <meta charset="utf-8">
  <script src="https://d3js.org/d3.v4.min.js"></script>
  <style>
    body {
      margin: 0;
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
    }
  </style>
</head>

<body>
  <script>
    // Feel free to change or delete any of the code you see in this editor!
    var svg = d3.select("body").append("svg")
      .attr("width", 300)
      .attr("height", 100);

    svg.append('defs').append('marker')
      .attr('id', 'arrow')
      .attr('viewBox', '0 0 10 6')
      .attr('refX', 10)
      .attr('refY', 3)
      .attr('markerWidth', 10)
      .attr('markerHeight', 6)
      .attr('markerUnits', 'userSpaceOnUse')
      .attr('orient', 'auto')
      .append('path')
      .attr('d', 'M 0 0 L 10 3 L 0 6 Z');

    svg.append('g')
      .attr('transform', 'translate(10,10)')
      .selectAll('path')
      .data(d3.range(4))
      .enter()
      .append('path')
      .style('stroke', 'black')
      .style('fill', 'none')
      .attr('marker-end', 'url(#arrow)')
      .attr('d', function(d, i) {
        return 'M 0 0 L 50 ' + i * 20;
      })
  </script>
</body>