一、核心配置项详解
1. 链接力(Link Force)
typescript
interface LinkConfig {
id?: (edge: EdgeDatum, index: number, edges: EdgeDatum[]) => string;
distance?: number | ((edge: EdgeDatum) => number); // 边理想长度
strength?: number | ((edge: EdgeDatum) => number); // 边拉力强度(0-1)
iterations?: number; // 迭代次数
}
// 示例:动态设置边长度
link: {
distance: (d) => d.weight * 50 + 100, // 根据权重计算长度
strength: 0.8
}
2. 多体力(Many-Body Force)
typescript
interface ManyBodyConfig {
strength?: number | ((node: NodeDatum) => number); // 节点间作用力(正吸引/负排斥)
theta?: number; // Barnes-Hut算法精度参数(默认0.9)
distanceMin?: number; // 最小作用距离
distanceMax?: number; // 最大作用距离
}
// 示例:设置动态斥力
manyBody: {
strength: (node) => node.degree * -30, // 节点度数越大斥力越强
theta: 0.8
}
3. 碰撞力(Collide Force)
typescript
interface CollideConfig {
radius?: number | ((node: NodeDatum) => number);
strength?: number;
iterations?: number;
}
// 示例:防止节点重叠
collide: {
radius: (d) => d.size + 5, // 动态碰撞半径
strength: 0.8
}
二、完整配置模板
javascript
const graph = new G6.Graph({
layout: {
type: 'd3-force',
/* 物理模拟核心配置 */
alpha: 0.3, // 初始热力值
alphaDecay: 0.0228, // 热力衰减速率
alphaMin: 0.001, // 停止模拟阈值
velocityDecay: 0.4, // 速度衰减系数
/* 作用力配置 */
link: { // 链接力(边弹簧)
id: (d) => d.id, // 边ID匹配器
distance: 150, // 默认边长度
strength: 0.5
},
manyBody: { // 多体力(电荷力)
strength: -1000, // 负值为斥力
theta: 0.8
},
collide: { // 碰撞力
radius: 30, // 碰撞半径
strength: 0.7
},
}
});
三、动态控制示例
1. 运行时修改参数
javascript
// 获取布局实例
const layout = graph.getLayout();
// 更新链接力配置
layout.setLayout({
link: {
distance: 200,
strength: (d) => d.weight * 0.5
}
});
四、Vue3集成最佳实践
vue
<script setup>
import G6 from '@antv/g6';
import { shallowRef, onMounted, onBeforeUnmount } from 'vue';
const graph = shallowRef(null);
const container = ref(null);
// 初始化图表
onMounted(() => {
graph.value = new G6.Graph({
container: container.value,
width: 1200,
height: 800,
layout: {
type: 'd3-force',
link: { distance: 100 },
manyBody: { strength: -800 },
collide: { radius: 25 }
}
});
// 加载数据
graph.value.read({
nodes: [...],
edges: [...]
});
});
// 组件卸载时销毁
onBeforeUnmount(() => {
graph.value.destroy();
});
</script>
<template>
<div ref="container" class="w-full h-[800px]"></div>
</template>
五、性能优化策略
- Barnes-Hut优化
通过theta
参数控制计算精度:
javascript
manyBody: {
strength: -500,
theta: 1.0 // 值越大计算越快精度越低
}
- 作用力迭代控制
减少非必要迭代次数:
javascript
link: {
iterations: 1 // 默认1次迭代
},
collide: {
iterations: 1
}
- Web Worker支持
javascript
const layout = new G6.Layout['d3-force']({
workerEnabled: true,
workerScriptURL: 'https://unpkg.com/@antv/layout@latest/dist/layout.worker.js'
});
六、调试技巧
javascript
// 获取物理模拟器实例
const simulation = graph.getLayoutInstance().forceSimulation;
// 监控节点速度
simulation.nodes().forEach(node => {
console.log(`Node ${node.id} velocity: [${node.vx},${node.vy}]`);
});
// 手动触发迭代
simulation.tick(5); // 推进5步迭代
G6官方文档,适用于v5.0.42+版本。