vue2 G6绘制辐射状布局图
最近需要用G6绘制描述实体间语义关系的图
最终效果图如下:
<div id="container"></div>
const fetchData = async (type) => {
const nodeData = [
{
id: "node1",
label: "产业园区",
style: {
fill: '#1890ff', // 填充颜色
},
},
{
id: "node2",
label: "科教文卫",
children: [
{ id: "node21", label: "空间包含" },
{ id: "node22", label: "空间被包含" },
],
},
{
id: "node3",
label: "普通房屋",
children: [
{ id: "", label: "" },
{ id: "", label: "" },
],
},
{
id: "node4",
label: "围墙", children: [ { id: "", label: "" } ]
},
{
id: "node5",
label: "主干路", children: [ { id: "", label: "" } ]
},
{
id: "node6",
label: "人工地理实体地名", children: [ { id: "", label: "" },{ id: "", label: "" } ]
},
],
const edgeData = [
{ source: "node1", target: "node2", label: "相邻"},
{ source: "node1", target: "node3", label: "西方"},
{ source: "node1", target: "node4", label: "空间包含"},
{ source: "node1", target: "node5", label: "下方"},
{ source: "node1", target: "node6", label: "北东北方"}
]
return {
nodes: nodeData,
edges: edgeData,
};
};
init(){
const container = document.getElementById('container');
const width = document.getElementById('container').scrollWidth;
const height = document.getElementById('container').scrollHeight || 500;
this.graph = new G6.Graph({
container,
modes: {//交互事件:拖动画布,拖拽节点,选中节点,缩放画布
default: [ 'drag-canvas', 'drag-node', 'click-select', 'zoom-canvas' ]
},
layout: {
type: "radial",
linkDistance: 200, // 调整节点之间的距离
preventOverlap: true,
nodeStrength: -1000, // 节点之间的斥力强度
edgeStrength: 0.1, // 边的引力强度
},
width,
height,
// data,
defaultNode: {
size: 50,
style: {
fill: '#a6d936',
stroke: '#a6d936',
},
labelCfg: { // 标签配置属性
position: 'bottom'
}
},
defaultEdge: {
style: {
stroke: '#ddd',
lineWidth: 2,
endArrow: true
},
},
});
this.graph.on('node:click', this.handleNodeClick);//节点点击事件
this.graph.render();
}
initData(type = ""){
fetchData(type).then((dataObj) => {
if (!dataObj) {
console.error('无数据');
return;
}
this.graph.data(dataObj);
this.graph.render();
})
},
handleNodeClick(ev) {
const node = ev.item;
const model = node.getModel();
if(model.id == "node1") return;
this.clickedInfo = model;
console.log('Node clicked:', this.clickedInfo, model.id, model.label);
if (this.selectedNodeId) {//清除原样式
const prevNode = this.graph.findById(this.selectedNodeId);
if (prevNode) {
prevNode.update({
style: {
fill: '#a6d936',
stroke: '#a6d936',
},
});
}
}
node.update({//给点击节点添加新样式
style: {
stroke: '#1890ff',
lineWidth: 3
},
});
this.selectedNodeId = model.id;
}