我正在使用sigma.js开发一个项目,我想在forceAtlas2运行时动态添加和删除主图中的子图。我是一个JS新手,所以我的问题可能是JavaScript问题,但我无法解决它们。
这是将图形图形加载到Sigma实例中的功能:
function loadGraph (json) {
console.log ("load graph");
sigInst.stopForceAtlas2();
$.getJSON(json, function (data) {
var edges = data.edges;
var nodes = data.nodes;
$.each(nodes, function (index, value) {
addNode(value.label, value.x, value.y, value.id, value.size, value.color);
});
$.each(edges, function (index, value) {
addEdge(value.source, value.target, value.id, value.weight);
});
});
sigInst.draw(2,2,2);
}
这是addNode函数:
function addNode (label, x, y, id, size, color) {
if (!sigInst.hasNode(id)) {
sigInst.addNode(id,{
'x': x,
'y': y,
label: label,
size:size,
color: color
});
console.log ("added node " + id);
}
else {
var nodeExisting = sigInst.getNodes(id);
var exSize = parseInt(nodeExisting.size);
console.log ("node " + id + " former size: "+ exSize);
exSize += parseInt(size);
nodeExisting.size = exSize;
console.log ("node " + id + " size now: " + exSize);
}
sigInst.draw();
}
和addEdge函数:
function addEdge (source, target,id, weight) {
if (!sigInst.hasEdge(id)) {
sigInst.addEdge(id, source, target, weight).draw();
}
else {
var edgeExisting = sigInst.getEdges(id);
//console.log("existing weight: " + edgeExisting.weight);
var exSize = parseInt(edgeExisting.weight);
exSize += parseInt(weight);
edgeExisting.weight = exSize;
//console.log("modified weight: " + edgeExisting.weight + " (" + edgeExisting.source + " -> " + edgeExisting.target + ")");
}
}
为了实现这一点,我在sigma.min.js中添加了两个函数:
this.hasNode = function(id){return typeof(b.graph.nodesIndex[id]) != 'undefined';};
和
this.hasEdge = function (id) {return typeof(b.graph.edgesIndex[id])!='undefined';};
我的问题是addNode函数并没有真正增加现有节点的大小。我来自Java,我知道在JavaScript中现有节点可能不是通过引用传递的,所以我不能修改字段并期望sigInst对象反映这一点,但我不知道该怎么做。如果有人能提供帮助,我将非常感激。提前谢谢!
答案 0 :(得分:3)
好的,解决了:我为sigma.min.js添加了两个函数:
this.setEdgeWeight = function(id,n){b.graph.edgesIndex[id].weight=n;}
和
this.setNodeSize = function(id,n){b.graph.nodesIndex[id].size=n;};
我显然很懒惰。也许有人可以从这些功能中受益。