Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vis.js network: how to add a node on click inside the canvas?

Manipulation methods of vis.js only include addNodeMode(), but not something like addNode(). I wonder if there's some nice way to create a node on click. May be by manipulating the data instead of network itself?

Of'course, one may go

network.on('click',function(params){
    if((params.nodes.length == 0) && (params.edges.length == 0)) {
        network.addNodeMode(); // doesn't add, one more click needed
        //# generate click in the same place. Use params.pointer.canvas
        //  or params.pointer.DOM to set appropriate coordinates
    }
})

but then we have also to prevent infinit loops since we generate a click event in a click handler..

like image 956
YakovL Avatar asked Feb 28 '18 15:02

YakovL


2 Answers

Ok, here's my current implementation:

...
data = ...
nodes = new vis.DataSet(data.nodes); // make nodes manipulatable
data = { nodes:nodes, edges:edges };
...
var network = new vis.Network(container, data, options);

network.on('click',function(params){
    if((params.nodes.length == 0) && (params.edges.length == 0)) {
        var updatedIds = nodes.add([{
            label:'new',
            x:params.pointer.canvas.x,
            y:params.pointer.canvas.y
        }]);
        network.selectNodes([updatedIds[0]]);
        network.editNode();
    }
})

It's not perfect since it actually creates a node and starts editing it, so if we cancel editing, the node stays. It also creates unwanted shadows of nodes. But it's already a working prototype which is enough to start with.

like image 70
YakovL Avatar answered Oct 18 '22 05:10

YakovL


You can add nodes dynamically by using the update method of the vis.DataSet class. See this documentation page for details: https://visjs.github.io/vis-data/data/dataset.html

like image 32
pgoldweic Avatar answered Oct 18 '22 05:10

pgoldweic