D3.js

在绘制节点链接图时,有时会存在这样的需求:我们需要固定某些节点的坐标,而其它节点遵循力导向布局,坐标位置不断变换,直到得到稳定的布局结果

效果图如下图所示,红色节点是固定了坐标的节点,灰色节点没有固定坐标,在力导向布局过程中红色节点的坐标始终不会发生变化。

在线演示:

在 D3.js 中,如果想要某个节点固定在一个位置,可以指定以下两个额外的属性:

  • fx - 节点的固定 x-位置
  • fy - 节点的固定 y-位置

每次 tick 结束后,节点的 node.x 会被重新设置为 node.fx 并且 node.vx 会被设置为 0;同理 node.y 会被重新替换为 node.fy 并且 node.vy 被设置为 0;如果想要某个节点解除固定,则将 node.fx 和 node.fy 设置为 null 或者删除这两个属性。

下面是使用D3.js V5版本的实现代码:

<html lang="en">
<head><meta charset="UTF-8"><title>Force layout</title><style>.link {stroke: #000;stroke-width: 1.5px;}.unfixedNode {cursor: move;fill: #ccc;stroke: #000;stroke-width: 1.5px;}.fixedNode {cursor: move;fill: red;stroke: #000;stroke-width: 1.5px;}</style>
</head>
<body><script src=".v5.min.js"></script><script>// fixed是固定坐标的节点,unfixed是没有固定坐标的节点。var graph ={"nodes": [{"id": 0, "category": "unfixed"},{"id": 1, "category": "ufixed"},{"id": 2, "category": "unfixed"},{"id": 3, "category": "fixed","x": 467, "y": 314},