如何让 Cytoscape.js canvas 尊重其 parent 的位置

How to make a Cytoscape.js canvas respect its parent's position

我有一个 React 组件,一旦从服务器获取了一些数据,它就会呈现一个 Cytoscape dagre 图。它似乎渲染了一个 canvas,它占据了 parent <div id="cy" /> 的右半部分。调用 cy.center()cy.fit() 居中并使图形本身适合 parent div,但只显示了一半的可视化,因为包含的 canvas 是一半屏幕。

设置以下 CSS:

position: absolute;
left: 0;
right: 0;

在容器上,与所有在线示例一样,将使 canvas 居中,但会中断文档流。它也没有解决半尺寸问题。

JSX:

  if (moduleStructure) {
    return (
      <div
        id="cy-module-structure"
        style={{
          position: "absolute",
          left: 0,
          top: 0,
          height: "500px",
          width: "1500px",
          display: "block",
        }}
      />
    );
  }

图形生成代码。这是在获取数据后由 React 挂钩调用的。

  function generateGraph(nodes, edges) {
    cytoscape.use(dagre);
    const cy = cytoscape({
      container: document.getElementById("cy-module-structure"),
      boxSelectionEnabled: false,
      autounselectify: true,
      layout: {
        name: "dagre",
        nodeDimensionsIncludeLabels: true,
      },
      zoom: 1,
      pan: { x: 0, y: 0 },
      style: [
        {
          selector: "node",
          style: {
            content: "data(label)",
            "text-valign": "center",
            "text-halign": "center",
            "background-color": "#11479e",
          },
        },
        {
          selector: "edge",
          style: {
            width: 4,
            "target-arrow-shape": "triangle",
            "line-color": "#9dbaea",
            "target-arrow-color": "#9dbaea",
            "curve-style": "bezier",
          },
        },
      ],
      elements: {
        nodes,
        edges,
      },
    });

    cy.ready(() => {
      cy.center();
      cy.fit();
      cy.resize();
    });
  }

最后 parent JSX:

      <div className="top-flex"> // flex-direction: row: 
        <Diagram /> // Cytoscape component
        <div className="basic-info">
          <H3>TEXT</H3>
          <small>INFO</small>
        </div>
      </div>

理想情况下,图表应占据 parent div 的整个宽度。在截图中可以看到上面描述的效果。

(1) 您调整大小和适合的顺序颠倒了。如果您之后要调整大小,则适合没有意义。拟合发生在可用范围内。

(2) 确保仅在 componentDidMount().

之后挂载 Cytoscape

(3) container 必须类似于 position:relativeposition:absolute(绝对不是 position:static),以便 container 的子级可以是相对于 container 定位。 Cytoscape.js 将默认设置 position:relative,因此除非您覆盖它,否则它是明智的设置。

问题是应用了更高级别的样式 text-align: center。删除它应该正确对齐。