forked from clay/er-top
1
0
Fork 0
er-top/src/views/graph/index.js

140 lines
4.2 KiB
JavaScript

/**
* @author: clay
* @data: 2021/5/15 0:01
* @email: clay@hchyun.com
* @description: node
*/
import * as d3 from 'd3-force/dist/d3-force'
import {renderMap} from '../create'
const initGraph = {
commonGraph:function(G6,options){
var graphData = options.graphData
const graph = new G6.Graph({
container:options.container,
defaultNode: {
size: [300, 400],
type: 'dice-er-box',
color: '#5B8FF9',
style: {
fill: '#9EC9FF',
lineWidth: 3,
},
labelCfg: {
style: {
fill: 'black',
fontSize: 20,
},
},
},
//设置edge默认属性
defaultEdge: {
type: 'dice-er-edge',
style: {
stroke: '#e2e2e2',
lineWidth: 4,
endArrow: true,
},
},
modes: {
default: ['dice-er-scroll', 'drag-node', 'drag-canvas'],
},
layout: {
type: 'dagre',
rankdir: 'LR',
align: 'UL',
controlPoints: true,
nodesepFunc: () => 0.2,
ranksepFunc: () => 0.5,
},
animate: true,
})
// 将 read 方法分解成 data() 和 render 方法,便于整个生命周期的管理
renderMap(graph,graphData)
return graph;
},
/**
* 力导布局
* @param G6
* @param options
* @returns {*}
*/
forceLayoutGraph: function(resolve, G6, options) {
let graphData = options.graphData
// let themeStyle = theme.defaultStyle // todo...先使用默认主题,后期可能增加其它风格的主体
// 生成G6实例
let graph = new G6.Graph({
container: options.container,
width: options.width,
height: options.height,
// nodeStateStyles: themeStyle.nodeStyle,
// edgeStateStyles: themeStyle.edgeStyle
})
// 初始化力导布局
let simulation = d3
.forceSimulation()
.force(
'link',
d3
.forceLink()
.id(function(d) {
return d.id
})
.distance(linkDistance)
.strength(0.5)
)
.force('charge', d3.forceManyBody().strength(-500).distanceMax(500).distanceMin(100))
.force('center', d3.forceCenter(options.width / 2, options.height / 2))
// 定义节点数据
simulation.nodes(graphData.nodes).on('tick', ticked)
// 定义连线数据
let edges = []
for (let i = 0; i < graphData.edges.length; i++) {
edges.push({
id: graphData.edges[i].id,
source: graphData.edges[i].source,
target: graphData.edges[i].target
})
}
simulation.force('link').links(edges)
graph.data(graphData)
graph.render()
// eslint-disable-next-line no-unused-vars
function linkDistance(d) {
return 150
}
function ticked() {
// protect: planA: 移除事件监听器 planB: 手动停止力模拟
if (graph.destroyed) {
// simulation.nodes(graphData.nodes).on('tick', null)
simulation.stop()
return
}
if (!graph.get('data')) {
// 若是第一次渲染,定义数据,渲染
graph.data(graphData)
graph.render()
} else {
// 后续渲染,直接刷新所有点和边的位置
graph.refreshPositions()
}
}
// 控制时间: 只布局10秒
let t = setTimeout(function() {
simulation.stop()
resolve(graph)
}, 10000)
// 判断force-layout结束
simulation.on('end', () => {
clearTimeout(t)
resolve(graph)
})
}
}
export default initGraph