You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-graph-vis中如何获取渲染后各节点的x、y坐标

react-graph-vis获取节点坐标实现方案

完全可以通过network实例拿到所有节点的x、y坐标,之前没找到相关属性,是因为坐标没有直接作为属性挂载在实例上,需要调用vis-network原生提供的内置方法获取。

核心方法说明

getNetwork回调返回的就是底层vis-network的原生实例,直接调用实例上的getPositions()方法即可获取坐标:

  • 不传参数:返回所有节点的坐标对象,结构为{ 节点id: {x: 横坐标值, y: 纵坐标值} }
  • 传入指定节点id:返回对应单个节点的坐标对象

注意:如果开启了物理引擎(physics为true),需要等布局计算稳定后再取坐标,否则会拿到布局过程中的临时中间值,结果不准确。你当前代码里设置了physics:false,渲染完成后坐标就固定了,稳妥起见还是可以通过布局稳定事件触发取值。

完整可运行代码示例

import React, { useRef } from "react";
import ReactDOM from "react-dom";
import Graph from "react-graph-vis";

function App() {
  // 存储network实例
  const networkRef = useRef(null);
  const graph = {
    nodes: [
      { id: 1, label: "Node 1", title: "node 1 tootip text" },
      { id: 2, label: "Node 2", title: "node 2 tootip text" },
      { id: 3, label: "Node 3", title: "node 3 tootip text" },
      { id: 4, label: "Node 4", title: "node 4 tootip text" },
      { id: 5, label: "Node 5", title: "node 5 tootip text" }
    ],
    edges: [
      { from: 1, to: 2 },
      { from: 1, to: 3 },
      { from: 2, to: 4 },
      { from: 2, to: 5 }
    ]
  };

  const options = {
    width: window.innerWidth + 'px',
    height: window.innerHeight + 'px', // 修正原代码高度取innerWidth的笔误
    layout: {
      hierarchical: false
    },
    edges: {
      color: "#000000"
    },
    physics: false,
    interaction: {
      dragNodes: true,
      zoomView: true,
      dragView: true 
    }
  };
  const events = {
    select: function(event) {
      const { nodes, edges } = event;
    },
    // 布局计算稳定后触发,此时坐标是最终值
    stabilized: function() {
      const allNodePositions = networkRef.current.getPositions();
      console.log('所有节点坐标:', allNodePositions);
    },
    // 如果需要拖拽节点后获取最新坐标,加这个事件
    dragEnd: function() {
      const latestPositions = networkRef.current.getPositions();
      console.log('拖拽后最新坐标:', latestPositions);
    }
  };
  return (
    <Graph
      graph={graph}
      options={options}
      events={events}
      getNetwork={network => {
        networkRef.current = network;
      }}
    />
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

补充说明

  • 不需要通过ref去遍历network实例的自有属性找坐标,vis-network把节点位置存在内部状态中,只对外暴露getPositions方法供外部读取,这是之前翻实例没找到坐标属性的核心原因。
  • 如果需要把坐标持久化存在节点数据里,拿到坐标结果后遍历更新自己的graph.nodes数组即可。

内容的提问来源于stack exchange,提问作者LIOR AVIV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 02:21:15