将tick()从d3 v3转换为v5

时间:2019-05-01 19:56:53

标签: javascript d3.js

我有一个force函数可以在d3 V3中使用,我想将其转换为V5。我将展示当前有效的解决方案,然后介绍出现问题的地方。

这在v3版本中有效

var force = d3.layout.force()
    .nodes(nodes)
    .size([width, height])
    .gravity(0)
    .charge(0)
    .friction(.9)
    .on("tick", tick)
    .start();

function tick(e) {

  var k = 0.03 * e.alpha;

  // Push nodes toward their designated focus.
  nodes.forEach(function(o, i) {
    var curr_act = o.act;

    var damper = .85;

    o.x += (x(+o.decade) - o.x) * k * damper;
    o.y += (y('met') - o.y) * k * damper;
    o.color = color('met');

 });

  circle
      .each(collide(.5))
      .style("fill", function(d) { return d.color; })
      .attr("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; });
}

// Resolve collisions between nodes.
function collide(alpha) {

  var quadtree = d3.geom.quadtree(nodes);

  return function(d) {
    var r = d.radius + maxRadius + padding,
        nx1 = d.x - r,
        nx2 = d.x + r,
        ny1 = d.y - r,
        ny2 = d.y + r;
    quadtree.visit(function(quad, x1, y1, x2, y2) {

      if (quad.point && (quad.point !== d)) {
        var x = d.x - quad.point.x,
            y = d.y - quad.point.y,
            l = Math.sqrt(x * x + y * y),
            r = d.radius + quad.point.radius + (d.act !== quad.point.act) * padding;
        if (l < r) {
          l = (l - r) / l * alpha;
          d.x -= x *= l;
          d.y -= y *= l;
          quad.point.x += x;
          quad.point.y += y;
        }
      }
      return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
    });
  };
}

其中对象circles被定义为。

var circle = svg.selectAll("circle")
    .data(nodes)
    .enter().append("circle")

this是一个节点的例子。

这是我尝试将其转换为v5

var force = d3.forceSimulation(nodes)
.velocityDecay(.9)
.force("center", d3.forceCenter(width / 2,height / 2))
.force("charge", d3.forceManyBody().strength())
.on("tick", tick)

除了将d3.geom.quadtree(nodes)替换为d3.quadtree(nodes)之外,其他所有内容均保持不变。

我在使用tick函数时遇到麻烦。在旧版本中,e参数打印出类似这样的内容。

enter image description here

在新版本中,它打印未定义,并且功能以Uncaught TypeError: Cannot read property 'alpha' of undefined中断。

tick()是否具有新的格式或在v5中传递参数的新方法?

1 个答案:

答案 0 :(得分:1)

如果您在模拟的滴答声中尝试访问模拟属性,则不再使用作为参数传递给滴答函数的事件。相反,您可以使用this直接访问模拟。

从文档中

  

调度指定事件时,将使用此上下文作为模拟来调用每个侦听器。 (docs)。

这意味着您可以在v4 / v5的刻度功能内使用this.alpha()(或simulation.alpha())访问alpha:

d3.forceSimulation()
  .velocityDecay(.9)
  .force("charge", d3.forceManyBody().strength())
  .on("tick", tick)  
  .nodes([{},{}]);
  
function tick() {
  console.log(this.alpha());
}
.as-console-wrapper {
  min-height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>