how do you set a fixed link distance with d3 v4

后端 未结 3 1255
攒了一身酷
攒了一身酷 2021-02-07 12:15

All the API examples seem to be for v3 still. I\'m trying to understand how to create a force graph with links of a fixed distance, like: http://bl.ocks.org/d3noob/5141278

相关标签:
3条回答
  • 2021-02-07 13:15

    You are almost there... check this out, this code works for me..

    Note: I'm getting length of links dynamically based on node labels with this code GetNodeDefaults(d.label).linkDistance i.e, it can be 100 or 200 or 300 etc.,

    var forceLink = d3
        .forceLink().id(function (d) {
            return d.id;
        })
        .distance(function (d) {
            return GetNodeDefaults(d.label).linkDistance;
        })
        .strength(0.1);
    
    var simulation = d3.forceSimulation()
        .force("link", forceLink)
        .force("charge", d3.forceManyBody().strength(function (d, i) {
            var a = i == 0 ? -2000 : -1000;
            return a;
        }).distanceMin(200).distanceMax(1000))
        .force("center", d3.forceCenter(width / 2, height / 2))
        .force("y", d3.forceY(0.01))
        .force("x", d3.forceX(0.01))
        .on("tick", ticked);
    
    0 讨论(0)
  • 2021-02-07 13:15

    you may try without force('center')

    let simulation = d3.forceSimulation()
      .force("link", d3.forceLink().id(function(d) { return d.id; }))
      .force("charge", d3.forceManyBody().strength(-150));
    
    0 讨论(0)
  • 2021-02-07 13:17

    You are closer to change the distance in v4! Check this change... it works for me:

        var simulation = d3.forceSimulation()
        .force("link", d3.forceLink().id(function(d, i) { return i; }).distance(100).strength(1))
        .force("charge", d3.forceManyBody())
        .force("center", d3.forceCenter(width / 2, height / 2));
    

    The original code was almost correct. However, the i needs to be added to the function, and i also needs to be returned in order to change the link distance. I edited the original code to reflect this. Please see this link: Link to Free Code Camp

    0 讨论(0)
提交回复
热议问题