仅在某些节点D3上使用径向力

时间:2018-10-26 13:53:16

标签: javascript d3.js

我有这个fiddle

我对节点进行了颜色编码,并希望这些节点不受径向力的影响。我认为这可能会起作用:

 function radial() {
      simulation
        .force("charge", d3.forceCollide().radius(10))
        .force("r", d3.forceRadial(function(d) {
          if(d.id == 3){
             return null //dont effect these nodes
          }else
          if (d.id < 5) {
            return 100;
          } else {
            return 200;
          }
        }, width / 2, height / 2).strength(1))
      simulation.alpha(1).restart()    
    }

但是,这似乎只是将它们放置在中间而没有跳过它们。是否有另一种方法可以过滤掉这些节点,以使径向力不会移动它们?

1 个答案:

答案 0 :(得分:1)

在强制访问器上返回null时,实际上是将这些节点的圆半径设置为(0,0)。根据文档:

d3.forceRadial()

  

朝以⟨x,y⟩为中心的指定半径的圆创建新的定位力。如果未指定x和y,则默认为⟨0,0⟩。

您想要做的是,将相应节点的力强度设置为0。您还需要关闭初始化模拟时设置的所有其他力:

function radial() {
  simulation
    .force("charge", d3.forceCollide().radius(10))
    .force("r", d3.forceRadial(function(d) {
        return d.id < 5 ? 100 : 200;
      }, width / 2, height / 2).strength(function(d) {
        // set radial force to 0 if it has the id we're looking for
        if(d.id == 3) return 0
        // otherwise keep the strength at 1
        else return 1
      })
    )
    // turning off previously set forces
    .force('link', null)
    .force('x', null)
    .force('y', null)