Where is d3.svg.diagonal()?

前端 未结 3 1572

I was trying to execute the code of collapsible-tree as mentioned here. But it seems the diagonal method is not applicable in v4 (I may be wrong).

For:

         


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 05:05

    D3 version 4.9.0 introduced link shapes, which have the same functionality of the old d3.svg.diagonal in D3 v3.

    According to the API:

    The link shape generates a smooth cubic Bézier curve from a source point to a target point. The tangents of the curve at the start and end are either vertical, horizontal or radial.

    There are three methods:

    • d3.linkHorizontal()
    • d3.linkVertical()
    • d3.linkRadial()

    So, for a collapsible tree like that one you linked, you define the path d attribute as:

    .attr("d", d3.linkHorizontal()
        .x(function(d) { return d.y; })
        .y(function(d) { return d.x; }));
    

    Demo:

    Suppose you have an object with source and target, each one with x and y properties:

    var data = {
      source: {
        x: 20,
        y: 10
      },
      target: {
        x: 280,
        y: 100
      }
    };
    

    First, you create the link generator:

    var link = d3.linkHorizontal()
      .x(function(d) {
        return d.x;
      })
      .y(function(d) {
        return d.y;
      });
    

    And then you can draw the path just by passing that data to the link generator:

    .attr("d", link(data))
    

    Here is the demo:

    var svg = d3.select("svg");
    
    var data = {
      source: {
        x: 20,
        y: 10
      },
      target: {
        x: 280,
        y: 100
      }
    };
    
    var link = d3.linkHorizontal()
      .x(function(d) {
        return d.x;
      })
      .y(function(d) {
        return d.y;
      });
    
    svg.append("path")
      .attr("d", link(data))
      .style("fill", "none")
      .style("stroke", "darkslateblue")
      .style("stroke-width", "4px");
    
    

提交回复
热议问题