图布局是指将图中的元素按照一定的规则进行排列的过程,例如基于电荷弹性模型的力导向布局、逐次排布的网格布局、基于层次结构的树布局等。
G6 提供了多种布局算法,用户可以根据自己的需求选择合适的布局算法:
其中 CompactBox Layout
、Dendrogram Layout
、Mindmap Layout
、Indented Layout
是树布局的一种,适用于树状结构的图。
你可以直接使用内置布局,如果想要使用其他布局,需要先进行注册:
import { register, ExtensionCategory } from '@antv/g6';import { CustomLayout } from 'package-name/or/path-to-your-custom-layout';register(ExtensionCategory.LAYOUT, 'custom-layout', CustomLayout);
通过 layout
配置项可以指定图的布局算法,例如:
{layout: {// 指定要使用的布局算法type: 'force',// 布局算法的配置项gravity: 10// ...}}
也可在图实例化之后使用 graph.setLayout
来更新布局配置。
G6 对一些布局算法提供了加速版本,包括:在 Web Worker 中执行布局算法、提供 WASM 版本的布局算法、GPU 加速的布局算法等。可按照下列方式使用:
除树布局外,G6 的所有内置布局算法都支持在 Web Worker 中执行。只需将 enableWorker
设置为 true
即可:
{layout: {type: 'force',enableWorker: true,// ...}}
目前支持 WASM 版本的布局算法有:Fruchterman Layout
ForceAtlas Layout
Force Layout
Dagre Layout
。
首先安装 @antv/layout-wasm
:
npm install @antv/layout-wasm --save
引入并注册布局算法:
import { register, Graph, ExtensionCategory } from '@antv/g6';import { FruchtermanLayout, initThreads, supportsThreads } from '@antv/layout-wasm';register(ExtensionCategory.LAYOUT, 'fruchterman-wasm', FruchtermanLayout);
初始化线程:
const supported = await supportsThreads();const threads = await initThreads(supported);
初始化图并传入布局配置:
const graph = new Graph({// ... 其他配置layout: {type: 'fruchterman-wasm',threads,// ... 其他配置},});
目前支持 GPU 加速的布局算法有:Fruchterman Layout
GForce Layout
。
首先安装 @antv/layout-gpu
:
npm install @antv/layout-gpu --save
引入并注册布局算法:
import { register, Graph, ExtensionCategory } from '@antv/g6';import { FruchtermanLayout } from '@antv/layout-gpu';register(ExtensionCategory.LAYOUT, 'fruchterman-gpu', FruchtermanLayout);
初始化图并传入布局配置:
const graph = new Graph({// ... 其他配置layout: {type: 'fruchterman-gpu',// ... 其他配置},});
通常,在调用 graph.render()
后,G6 会自动执行布局算法。
如果需要手动执行布局算法,G6 提供了以下 API:
如果内置布局算法无法满足需求,可以自定义布局算法,具体请参考自定义布局。