【问题标题】:Where does the repulsive force come from in this force based layout?在这种基于力的布局中,排斥力从何而来?
【发布时间】:2025-03-05 06:05:02
【问题描述】:

在 Mike Bostock 的这个块中,当您移动鼠标时,节点会被推开。从示例中的代码来看,我不明白这是怎么回事。

我看到一个节点在生成布局后已从节点数组中删除,其固定属性设置为 true,并且它的位置会根据鼠标移动进行更新,并且在滴答声期间不会对其进行操作。但从来没有任何力量分配给它。

看起来这种力量是神奇地创造出来的或以某种方式推断出来的。这里发生了什么?

var width = 640,
    height = 480,
    τ = 2 * Math.PI,
    gravity = .05;

var sample = poissonDiscSampler(width, height, 30),
    nodes = [{x: 0, y: 0}],
    s;

while (s = sample()) nodes.push(s);

var force = d3.layout.force()
    .size([width, height])
    .nodes(nodes.slice())
    .gravity(0)
    .charge(function(d, i) { return i ? -30 : -3000; })
    .on("tick", ticked)
    .start();

var voronoi = d3.geom.voronoi()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });

var root = nodes.shift();

root.fixed = true;

var links = voronoi.links(nodes);

var canvas = d3.select("body").append("canvas")
    .attr("width", width)
    .attr("height", height)
    .on("ontouchstart" in document ? "touchmove" : "mousemove", moved);

var context = canvas.node().getContext("2d");

function moved() {
  var p1 = d3.mouse(this);
  root.px = p1[0];
  root.py = p1[1];
  force.resume();
}

function ticked() {
  force.resume();

  for (var i = 0, n = nodes.length; i < n; ++i) {
    var node = nodes[i];
    node.y += (node.cy - node.y) * gravity;
    node.x += (node.cx - node.x) * gravity;
  }

  context.clearRect(0, 0, width, height);

  context.beginPath();
  for (var i = 0, n = links.length; i < n; ++i) {
    var link = links[i];
    context.moveTo(link.source.x, link.source.y);
    context.lineTo(link.target.x, link.target.y);
  }
  context.lineWidth = 1;
  context.strokeStyle = "#bbb";
  context.stroke();

  context.beginPath();
  for (var i = 0, n = nodes.length; i < n; ++i) {
    var node = nodes[i];
    context.moveTo(node.x, node.y);
    context.arc(node.x, node.y, 2, 0, τ);
  }
  context.lineWidth = 3;
  context.strokeStyle = "#fff";
  context.stroke();
  context.fillStyle = "#000";
  context.fill();
}

// Based on https://www.jasondavies.com/poisson-disc/
function poissonDiscSampler(width, height, radius) {
  var k = 30, // maximum number of samples before rejection
      radius2 = radius * radius,
      R = 3 * radius2,
      cellSize = radius * Math.SQRT1_2,
      gridWidth = Math.ceil(width / cellSize),
      gridHeight = Math.ceil(height / cellSize),
      grid = new Array(gridWidth * gridHeight),
      queue = [],
      queueSize = 0,
      sampleSize = 0;

  return function() {
    if (!sampleSize) return sample(Math.random() * width, Math.random() * height);

    // Pick a random existing sample and remove it from the queue.
    while (queueSize) {
      var i = Math.random() * queueSize | 0,
          s = queue[i];

      // Make a new candidate between [radius, 2 * radius] from the existing sample.
      for (var j = 0; j < k; ++j) {
        var a = 2 * Math.PI * Math.random(),
            r = Math.sqrt(Math.random() * R + radius2),
            x = s.x + r * Math.cos(a),
            y = s.y + r * Math.sin(a);

        // Reject candidates that are outside the allowed extent,
        // or closer than 2 * radius to any existing sample.
        if (0 <= x && x < width && 0 <= y && y < height && far(x, y)) return sample(x, y);
      }

      queue[i] = queue[--queueSize];
      queue.length = queueSize;
    }
  };

  function far(x, y) {
    var i = x / cellSize | 0,
        j = y / cellSize | 0,
        i0 = Math.max(i - 2, 0),
        j0 = Math.max(j - 2, 0),
        i1 = Math.min(i + 3, gridWidth),
        j1 = Math.min(j + 3, gridHeight);

    for (j = j0; j < j1; ++j) {
      var o = j * gridWidth;
      for (i = i0; i < i1; ++i) {
        if (s = grid[o + i]) {
          var s,
              dx = s.x - x,
              dy = s.y - y;
          if (dx * dx + dy * dy < radius2) return false;
        }
      }
    }

    return true;
  }

  function sample(x, y) {
    var s = {x: x, y: y, cx: x, cy: y};
    queue.push(s);
    grid[gridWidth * (y / cellSize | 0) + (x / cellSize | 0)] = s;
    ++sampleSize;
    ++queueSize;
    return s;
  }
}
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
</body>

【问题讨论】:

    标签: javascript d3.js data-visualization force-layout


    【解决方案1】:

    当然,这里没有魔法。这是您必须查看的行,在d3.layout.force()

    .charge(function(d, i) { return i ? -30 : -3000; })
    

    它说的基本上是这样的:

    对每个节点应用 -30 的费用,除非它是第一个。在这种情况下,收取 -3000 的费用。

    为什么?

    那是ternary operator。它将评估一个条件。如果条件为真,则执行第一个表达式,如果为假,则执行第二个。

    在 JavaScript 中,0 是虚假的,而所有其他正整数当然都是真实的。因为i 是索引,所以只有第一个索引(当i0 时)将评估为假。所有其他指数将评估为真。

    所以,对于第一个索引,我们有:

    return false ? -30 : -3000;
    //this will return -3000
    

    而对于我们拥有的所有其他索引:

    return true ? -30 : -3000;
    //this will return -30
    

    我们可以在下面的 sn-p 中清楚地看到这一点,我将 -3000 更改为 +3000。现在,第一个节点(光标所在的位置)将混乱地吸引而不是排斥:

    var width = 640,
        height = 480,
        τ = 2 * Math.PI,
        gravity = .05;
    
    var sample = poissonDiscSampler(width, height, 30),
        nodes = [{x: 0, y: 0}],
        s;
    
    while (s = sample()) nodes.push(s);
    
    var force = d3.layout.force()
        .size([width, height])
        .nodes(nodes.slice())
        .gravity(0)
        .charge(function(d, i) { return i ? -30 : +3000; })
        .on("tick", ticked)
        .start();
    
    var voronoi = d3.geom.voronoi()
        .x(function(d) { return d.x; })
        .y(function(d) { return d.y; });
    
    var root = nodes.shift();
    
    root.fixed = true;
    
    var links = voronoi.links(nodes);
    
    var canvas = d3.select("body").append("canvas")
        .attr("width", width)
        .attr("height", height)
        .on("ontouchstart" in document ? "touchmove" : "mousemove", moved);
    
    var context = canvas.node().getContext("2d");
    
    function moved() {
      var p1 = d3.mouse(this);
      root.px = p1[0];
      root.py = p1[1];
      force.resume();
    }
    
    function ticked() {
      force.resume();
    
      for (var i = 0, n = nodes.length; i < n; ++i) {
        var node = nodes[i];
        node.y += (node.cy - node.y) * gravity;
        node.x += (node.cx - node.x) * gravity;
      }
    
      context.clearRect(0, 0, width, height);
    
      context.beginPath();
      for (var i = 0, n = links.length; i < n; ++i) {
        var link = links[i];
        context.moveTo(link.source.x, link.source.y);
        context.lineTo(link.target.x, link.target.y);
      }
      context.lineWidth = 1;
      context.strokeStyle = "#bbb";
      context.stroke();
    
      context.beginPath();
      for (var i = 0, n = nodes.length; i < n; ++i) {
        var node = nodes[i];
        context.moveTo(node.x, node.y);
        context.arc(node.x, node.y, 2, 0, τ);
      }
      context.lineWidth = 3;
      context.strokeStyle = "#fff";
      context.stroke();
      context.fillStyle = "#000";
      context.fill();
    }
    
    // Based on https://www.jasondavies.com/poisson-disc/
    function poissonDiscSampler(width, height, radius) {
      var k = 30, // maximum number of samples before rejection
          radius2 = radius * radius,
          R = 3 * radius2,
          cellSize = radius * Math.SQRT1_2,
          gridWidth = Math.ceil(width / cellSize),
          gridHeight = Math.ceil(height / cellSize),
          grid = new Array(gridWidth * gridHeight),
          queue = [],
          queueSize = 0,
          sampleSize = 0;
    
      return function() {
        if (!sampleSize) return sample(Math.random() * width, Math.random() * height);
    
        // Pick a random existing sample and remove it from the queue.
        while (queueSize) {
          var i = Math.random() * queueSize | 0,
              s = queue[i];
    
          // Make a new candidate between [radius, 2 * radius] from the existing sample.
          for (var j = 0; j < k; ++j) {
            var a = 2 * Math.PI * Math.random(),
                r = Math.sqrt(Math.random() * R + radius2),
                x = s.x + r * Math.cos(a),
                y = s.y + r * Math.sin(a);
    
            // Reject candidates that are outside the allowed extent,
            // or closer than 2 * radius to any existing sample.
            if (0 <= x && x < width && 0 <= y && y < height && far(x, y)) return sample(x, y);
          }
    
          queue[i] = queue[--queueSize];
          queue.length = queueSize;
        }
      };
    
      function far(x, y) {
        var i = x / cellSize | 0,
            j = y / cellSize | 0,
            i0 = Math.max(i - 2, 0),
            j0 = Math.max(j - 2, 0),
            i1 = Math.min(i + 3, gridWidth),
            j1 = Math.min(j + 3, gridHeight);
    
        for (j = j0; j < j1; ++j) {
          var o = j * gridWidth;
          for (i = i0; i < i1; ++i) {
            if (s = grid[o + i]) {
              var s,
                  dx = s.x - x,
                  dy = s.y - y;
              if (dx * dx + dy * dy < radius2) return false;
            }
          }
        }
    
        return true;
      }
    
      function sample(x, y) {
        var s = {x: x, y: y, cx: x, cy: y};
        queue.push(s);
        grid[gridWidth * (y / cellSize | 0) + (x / cellSize | 0)] = s;
        ++sampleSize;
        ++queueSize;
        return s;
      }
    }
    <!DOCTYPE html>
    <meta charset="utf-8">
    <body>
    <script src="//d3js.org/d3.v3.min.js"></script>
    </body>

    【讨论】: