mxGraph缩放以适合视图

问题描述

如何缩放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.fitScales 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();

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...