将 `tick()` 从 d3 v3 转换为 v5

2023-12-20

我有一个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")

And this https://i.stack.imgur.com/9ZFIo.png是一个节点的例子。

这是我尝试将其转换为 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) with d3.quadtree(nodes).

我遇到了问题tick功能。在旧版本中,e参数打印出类似这样的内容。

在新版本中,它会打印 undefined 并且函数会中断Uncaught TypeError: Cannot read property 'alpha' of undefined.

Does tick()v5 中有新的格式或新的参数传递方式吗?


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

来自文档:

当指定的事件被调度时,每个监听器都会被调用,并以 this 上下文作为模拟。 (docs https://github.com/d3/d3-force#simulation_on).

这意味着您可以访问 alpha,例如:this.alpha() (or simulation.alpha()),在 v4/v5 的 tick 函数中:

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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 `tick()` 从 d3 v3 转换为 v5 的相关文章

随机推荐