关于D3.js 力导向图V3和V4节点固定

记录一点碰到的问题和解决方案。感觉国内关于D3.js 4.0版本的相关资料还是少。

力导向图布局

D3一种布局的方式,可以将你nodes links的节点数据转换成可以绘制的坐标点数据,然后通过svg展现出来,画拓扑图中用到。

通过fixed属性来固定节点

https://bl.ocks.org/mbostock/...

上面作者的demo(d3.js v4)。
力导向图的几个特征

  • 节点之间的相互作用力的存在 所以节点不能重合,然后节点拖拽的过程中会影响到其他的节点

  • 拖拽的过程 节点之间的线段长度不变,会会弹回去

但是对于拓扑图来说,这两点会有问题,并不需要这样的体验,简单来说,节点固定后,拖拽不影响其他节点的位置,节点拖拽链路长度要变动。

找了个作者的demo
sticky force layout
这是D3.js v3版本的实现方法
主要方法就是将节点数据

d.fixed = true;

一开始没有仔细看v4版本的API 想当然以为也是这样去做的,尝试了好久没成功。
v4版本的api对fixed节点的规定是 如果节点数据(d) 有fx fy两个值不为null,那么就是固定节点,unfix固定节点的方法就是 设置fx fy=null。

To fix a node in a given position, you may specify two additional properties:
fx - the node’s fixed x-position
fy - the node’s fixed y-position
At the end of each tick, after the application of any forces, a node with a defined node.fx has node.x reset to this value and node.vx set to zero; likewise, a node with a defined node.fy has node.y reset to this value and node.vy set to zero. To unfix a node that was previously fixed, set node.fx and node.fy to null, or delete these properties.

simulation_nodes

v4版本
http://codepen.io/jingxiao/pe...

其他

D3.js 3.x和4.x版本api改动真心大,也没有很多相关资料,还是要多看api吧

猜你喜欢

转载自blog.csdn.net/zoubf/article/details/53436903