vis.js学习(3)

需求

  1. 对canvas中的节点和边数据进行更改,包括增加新节点,修改节点的属性,删除节点的操作,通过对network的配置可以实现
  2. 上一篇中构建图标库并拖拽图标产生新节点,由于涉及到dom和canvas的转化,比较麻烦,暂时效果为:点击图标库中的图标,生成一个该实体类型的新节点

代码

html代码(修改节点属性的弹出框)

1
2
3
4
5
6
7
8
9
10
11
12
13
<div id="network-popUp">
<span id="operation">node</span> <br>
<table style="margin:auto;">
<tr>
<td>id</td><td><input id="node-id" value="new value" /></td>
</tr>
<tr>
<td>名称</td><td><input id="node-label" value="new value" /></td>
</tr>
</table>
<input type="button" value="save" id="saveButton" />
<input type="button" value="cancel" id="cancelButton" />
</div>

js中对network的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
var options = {
manipulation: {
addNode: function (data, callback) {
// filling in the popup DOM elements
document.getElementById('operation').innerHTML = "Add Node";
document.getElementById('node-id').value = data.id;
document.getElementById('node-label').value = data.label;
document.getElementById('saveButton').onclick = saveData.bind(this, data, callback);
document.getElementById('cancelButton').onclick = clearPopUp.bind();
document.getElementById('network-popUp').style.display = 'block';
},
editNode: function (data, callback) {
// filling in the popup DOM elements
document.getElementById('operation').innerHTML = "Edit Node";
document.getElementById('node-id').value = data.id;
document.getElementById('node-label').value = data.label;
document.getElementById('saveButton').onclick = saveData.bind(this, data, callback);
document.getElementById('cancelButton').onclick = cancelEdit.bind(this,callback);
document.getElementById('network-popUp').style.display = 'block';
},
addEdge: function (data, callback) {
if (data.from == data.to) {
var r = confirm("Do you want to connect the node to itself?");
if (r == true) {
callback(data);
}
}
else {
callback(data);
}
}
}
}

js中新增的函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function saveData(data,callback) {
data.id = document.getElementById('node-id').value;
data.label = document.getElementById('node-label').value;
clearPopUp();
callback(data);
}
function clearPopUp() {
document.getElementById('saveButton').onclick = null;
document.getElementById('cancelButton').onclick = null;
document.getElementById('network-popUp').style.display = 'none';
}

function cancelEdit(callback) {
clearPopUp();
callback(null);
}

在canvas中出现edit按钮,点击即可对canvas中的节点和边进行修改操作

参考

官方示例:vis-master\examples\network\other\manipulation.html