首页 > 解决方案 > (Vis.js 网络)getPositions 的节点坐标不正确?

问题描述

在我的vis.js 网络中,当我单击节点时,我想让一个弹出窗口出现在节点的位置。

我使用了getPositions方法,但弹出窗口出现在错误的位置(左上角太多),好像坐标不正确。

network.on("click", function (params) {
        // Get the node ID
        var nodeId = params.nodes[0];
        if (nodeId) {

            // Get the node title to show in the popup
            var popup = this.body.nodes[nodeId].options.title;

            // Get the node coordinates
            var nodePosition = network.getPositions(nodeId);
            var nodeX = nodePosition[nodeId].x;
            var nodeY = nodePosition[nodeId].y;

            // Show the tooltip in a div
            document.getElementById('popup').innerHTML = popup;
            document.getElementById('popup').style.display = "block";
            // Place the div
            document.getElementById('popup').style.position = "absolute";
            document.getElementById('popup').style.top = nodeY+'px';
            document.getElementById('popup').style.left = nodeX+'px';

        }
    });
    // Empty and hide the div when click elsewhere
    network.on("deselectNode", function (params) {
        document.getElementById('popup').innerHTML = null;
        document.getElementById('popup').style.display = "none";
    });

标签: javascriptpopupvis.jsvis.js-network

解决方案


我在github 的 vis 支持部分得到了一些帮助。原来诀窍是使用canvasToDOM().

以下是它如何应用于我的代码:

network.on("click", function(params) {
  // Get the node ID
  var nodeId = params.nodes[0];
  if (nodeId) {
    // Get the node title to show in the popup
    var popup = this.body.nodes[nodeId].options.title;

    // Get the node coordinates
    var { x: nodeX, y: nodeY } = network.canvasToDOM(
      network.getPositions([nodeId])[nodeId]
    );

    // Show the tooltip in a div
    document.getElementById("popup").style.display = "block";
    // Place the div
    document.getElementById("popup").style.position = "absolute";
    document.getElementById("popup").style.top = nodeY + "px";
    document.getElementById("popup").style.left = nodeX + "px";
  }
});

当网络保持不变时它可以工作,但在我的情况下,我想适应网络并放大点击的节点,所以弹出窗口不会跟随,但由于这是一个单独的问题,我将发布另一个问题。


推荐阅读