Search code examples
javascriptvis.jsvis.js-network

How to limit zooming of a vis.js network?


I've implemented a simple network using vis.js. Here's my code:

//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);

On performing the zoom-out operation multiple times the network disappears. Are there any functions to limit the zooming level?


Solution

  • I wrote you some code to get this function working since there is no zoomMax function within the network of vis.js, I wrote some basic logic to help you out.

    var container = document.getElementById('mynetwork');
    var data = {
        nodes: nodes,
        edges: edges
    };
    var afterzoomlimit = { //here we are setting the zoom limit to move to 
        scale: 0.49,
    }
    
    var options = {}; 
    
    var network = new vis.Network(container, data, options);
    network.on("zoom",function(){ //while zooming 
        if(network.getScale() <= 0.49 )//the limit you want to stop at
        {
            network.moveTo(afterzoomlimit); //set this limit so it stops zooming out here
        } 
    });
    

    Here is a jsfiddle: https://jsfiddle.net/styb8u9o/

    Hope this helps you.