This commit is contained in:
asp_ly 2024-12-13 20:51:11 +08:00
parent 45264109d0
commit 8186bdfba5

View File

@ -25,13 +25,46 @@ const hasAllNodesPosition = (nodes: NodeData[]) => {
};
/**
*
*
* @param graph
*/
const centerAndFit = (graph: Graph) => {
// 获取画布大小
const container = graph.container;
if (!container) return;
const containerBBox = container.getBoundingClientRect();
const padding = 40; // 设置更大的内边距
// 居中并缩放
graph.centerContent();
graph.zoomToFit({
padding,
maxScale: 1, // 限制最大缩放比例
minScale: 0.5, // 限制最小缩放比例
});
// 确保在视口中心
const graphBBox = graph.getBBox();
if (graphBBox) {
const tx = (containerBBox.width - graphBBox.width) / 2;
const ty = (containerBBox.height - graphBBox.height) / 2;
graph.translate(tx, ty);
}
};
/**
*
* @param graph
* @param nodes
*/
export const applyAutoLayout = (graph: Graph, nodes: NodeData[] = []) => {
// 如果所有节点都有位置信息,则不应用自动布局
// 如果所有节点都有位置信息,只进行居中显示
if (nodes.length > 0 && hasAllNodesPosition(nodes)) {
// 等待所有节点渲染完成后再居中
setTimeout(() => {
centerAndFit(graph);
}, 100);
return;
}
@ -39,10 +72,10 @@ export const applyAutoLayout = (graph: Graph, nodes: NodeData[] = []) => {
g.setGraph({
rankdir: 'LR',
align: 'UL',
ranksep: 80,
nodesep: 50,
marginx: 20,
marginy: 20,
ranksep: 100, // 增加节点间距
nodesep: 60, // 增加节点间距
marginx: 40, // 增加边距
marginy: 40,
});
g.setDefaultEdgeLabel(() => ({}));
@ -67,11 +100,14 @@ export const applyAutoLayout = (graph: Graph, nodes: NodeData[] = []) => {
// 应用布局结果
graphNodes.forEach(node => {
const nodeWithPosition = g.node(node.id);
node.position(
nodeWithPosition.x - nodeWithPosition.width / 2,
nodeWithPosition.y - nodeWithPosition.height / 2
);
if (nodeWithPosition) {
node.position(
nodeWithPosition.x - nodeWithPosition.width / 2,
nodeWithPosition.y - nodeWithPosition.height / 2
);
}
});
graph.centerContent();
// 居中显示并适应画布
centerAndFit(graph);
};