如何限制vis.js网络的缩放?

时间:2018-03-15 12:43:09

标签: javascript vis.js vis.js-network

我使用vis.js实现了一个简单的网络。这是我的代码:

//create an array of nodes
var nodes = [
    {
        id: "1",
        label: "item1"
    },
    {
        id: "2",
        label: "item2"
    },
    {
        id: "3",
        label: "item3"
    },
];

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

// create a network
var container = document.getElementById('mynetwork');

// provide the data in the vis format
var data = {
    nodes: nodes,
    edges: edges
};
var options = {};

// initialize your network!
var network = new vis.Network(container, data, options);

多次执行缩小操作时,网络消失。有没有限制缩放级别的功能?

3 个答案:

答案 0 :(得分:3)

我写了一些代码来使这个函数工作,因为vis.js网络中没有zoomMax函数,我写了一些基本的逻辑来帮助你。

Rotativa

这是一个jsfiddle:https://jsfiddle.net/styb8u9o/

希望这会对你有所帮助。

答案 1 :(得分:1)

您可以使用此代码更好,因为达到缩放限制时,您永远都不会进入网络中间:

//NetWork on Zoom
network.on("zoom",function(){
   pos = [];
   pos = network.getViewPosition();

   if(network.getScale() <= 0.49 )
   {

    network.moveTo({
        position: {x:pos.x, y:pos.y},
        scale: 0.49,
      });
   }
   if(network.getScale() >= 2.00 ){

        network.moveTo({
        position: {x:pos.x, y:pos.y},
        scale: 2.00,
      });
    }
  });

答案 2 :(得分:1)

这是一个保留最后位置的版本,以防止在到达最大范围时出现烦人的跳跃或缓慢平移。

let MIN_ZOOM = 0.5
let MAX_ZOOM = 2.0
let lastZoomPosition = {x:0, y:0}
network.on("zoom",function(params){
    let scale = network.getScale()
    if(scale <= MIN_ZOOM )
    {
        network.moveTo({
            position: lastZoomPosition,
            scale: MIN_ZOOM
        });
    }
    else if(scale >= MAX_ZOOM ){
        network.moveTo({
            position: lastZoomPosition,
            scale: MAX_ZOOM,
       });
     }
     else{
        lastZoomPosition = network.getViewPosition()
     }
});
network.on("dragEnd",function(params){
    lastZoomPosition = network.getViewPosition()
});

不过,一旦解决了以下问题,它将是多余的: https://github.com/visjs/vis-network/issues/574