使 Cytoscape.js 容器刚好够宽够长

Make Cytoscape.js container just wide enough and just long enough

我正在使用 Cytoscape.js.

在单独的 canvases 中渲染多个树布局

目前,每个 canvas 都被一个具有固定尺寸(例如 400x400)的容器 div 包裹着。 Cytoscape 提供了一种设置,可将每棵树放入其容器中,并将每棵树放大到一定程度,使整棵树在给定尺寸内可见。

我不想让每个布局都适合容器,而是想调整每个容器的大小以完美地容纳其子 canvas。换句话说,我需要一种方法来询问 Cytoscape canvas、"What width and height would you be at 0 zoom" 或 "how many pixels do you need in each direction to draw fully" 的每个实例,然后适当地调整每个容器的大小。

Cytoscape 确实提供了获取 canvas 的 width() and height() 的方法,但这些最终是实际尺寸(可能不适合容器),而不是 "desired" /需要尺寸。

我突然想到我可以想出一些启发式方法来根据节点和边缘的数量来设置容器的宽度和高度,但是这种方法还没有被证明是有效的;节点和边的数量告诉我关于最终布局和安排的信息很少,仅此一项就可以决定所需的宽度和高度。

您是否尝试过使用:

eles.boundingBox(options);

或:

eles.renderedBoundingBox();

'eles' 必须是这样的:

var eles = cy.elements();

您可以通过cytoscape 方法获取关于您的节点的两个主要信息: cytoscape中的实际位置和渲染位置,阅读这篇文章了解更多:

http://js.cytoscape.org/#notation/position

关于你的第二个问题:

只要调用

就可以很容易地对齐树
cy.fit(/*eles, padding*/); // Pan and zoom fitted to the tree
cy.center(/*eles*/); // Moves the graph to the exact center of your tree
cy.elements().shift('x', offset); // Moves the nodes to the right, offset must be negative to move them to the left