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

2

9

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..

Connolly answered 28/2, 2018 at 15:59 Comment(0)
C
7

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.

Connolly answered 2/3, 2018 at 12:57 Comment(0)
M
6

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

Mame answered 1/3, 2018 at 16:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.