D3 force layout start需要5秒才能执行

D3 force layout start takes 5 second to execute

我在我的项目中使用了d3,并在其中使用了force layout。

执行d3 force.start()函数后,在浏览器中布局和显示内容需要5秒。

This 示例仅使用 2 个节点的强制布局。简单吧?但是加载这些节点需要很长时间。

问题:这种布局是正常的还是有点错误的味道?

我认为您只是误解了示例。加载节点不需要 5 秒。布局冷却(稳定)需要 5 秒。

最初,节点是随机放置的,并发出了 start 事件。然后强制布局进入循环,重新计算节点位置并冷却布局(通过逐渐减小 alpha 值)。对于每个循环传递,都会发出一个 tick 事件。最后,当布局稳定后(alpha 足够接近于零),end 事件被触发。

示例中的代码仅在发出 end 事件时显示节点:

// We're about to tell the force layout to start its
// calculations. We do, however, want to know when those
// calculations are complete, so before we kick things off
// we'll define a function that we want the layout to call
// once the calculations are done.

force.on('end', function() { ...

您可以将其更改为 tick,如 this modified example,以立即查看节点。但是节点会一直跳动,直到布局稳定下来。

您可以在 Force Layout documentation. And here's information about force.on 中阅读有关强制布局的更多信息。