首页 > 解决方案 > vis-network在任何情况下如何获取节点中心和左上角的实时位置?

问题描述

jsfiddle 演示

.wrap{
  position: relative;
  margin: 100px auto 0;
  width: 400px;
  height: 400px;
  border: 1px solid black;
}
#mynetwork {
  width: 100%;
  height: 100%;
}
.origin {
  position: absolute;
  left: -5px;
  top: -5px;
  width: 10px;
  height: 10px;

  background: red;
  z-index: 1;
  border-radius: 50%;
}
<div class="wrap">
  <div id="mynetwork"></div>
  <div class="origin"></div>
</div>
        // create an array with nodes
    var nodes = [{
            id: 1,
      "shape": "dot",
            label: 'node1',
      x: 5,
      y: 5
         }, {
            id: 2,
      "shape": "dot",
            label: 'node2',
      x: 50,
      y: 75
         }];

    // create an array with edges
    var edges = [
        {from: 1, to: 2},
        {from: 1, to: 3}
    ];

    // create a network
    var container = document.getElementById('mynetwork');
    var data = {
        nodes: nodes,
        edges: edges
    };
    var options = {
        interaction: {
        hover: true,
      },
      physics: {
        enabled: false
      }
    };
    var network = new vis.Network(container, data, options);    
    network.on("hoverNode", function (t) {
        var nodeID = t.node;
      // I want to get the real-time position of the center of the node and the upper left corner under any circumstances (zoom in, zoom out, move)
        // ... ?
    });

希望能实时获取到节点和左上角的坐标。无论如何,例如放大时获得'node1'的位置。节点移动后,它是一个新的位置。它应该改变。应计算与红点的距离。

标签: javascriptvis.jsvis.js-networkvisnetwork

解决方案


    const node = network.getPositions([nodeID])[nodeID]
    const corner = visGraph.canvasToDOM({
      x: node.x,
      y: node.y
    })

参考GitHub vis-networkissues/128


推荐阅读