问题描述
如何缩放mxGraph以适合初始渲染时的视图?
我将容器的宽度和高度设置为100%。我想缩放在容器中呈现的mxgraph以适合容器。我该怎么办?
function addNodes(nodes,graph,parent) {
// Needed to connect the edges
const nodeData = new Object();
nodes.forEach((node) => {
nodeData[node.id] = graph.insertVertex(parent,null,node.title,100,20,'defaultVertex;fillColor=' + (node.error ? 'red' : 'green'));
})
return nodeData;
}
function addEdges(edges,nodes,parent) {
edges.forEach((edge) => {
graph.insertEdge(parent,'',nodes[edge.source],nodes[edge.target]);
})
}
export function mountGraph(containerName,data) {
const container = document.getElementById(containerName);
const graph = new mxGraph(container);
graph.getModel().beginUpdate();
const parent = graph.getDefaultParent();
const nodes = addNodes(data.nodes,parent);
addEdges(data.edges,parent);
const layout = new mxHierarchicalLayout(graph);
layout.execute(parent);
graph.getModel().endUpdate();
}
解决方法
您可以为此使用mxGraph.fit:Scales the graph such that the complete diagram fits into <container> and returns the current scale in the view.
请注意,如果在调用fit
函数之后调用mountGraph
,将执行2幅绘制/渲染。在graph.getModel().endUpdate()
调用之后的第一个,在graph.fit
调用之后的第二个。
为避免这种情况,由于我们想在渲染之前拟合初始图形,文档建议在更改模型之前将mxGraphView.rendering设置为false,并在拟合之后进行渲染。
在mountGraph
函数中,这可能类似于
graph.view.rendering = false;
graph.getModel().beginUpdate();
...
graph.getModel().endUpdate();
graph.fit();
graph.view.rendering = true;
graph.refresh();