Vis.js network: how to add a node on click inside the canvas?
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
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.