[英]Replacing contents of HTML canvas with Springy force-directed graph
我有一个使用Springy力导向图布局库的不错的力导向图。 我发现当我通过ajax将图形替换为另一个图形时(例如,在用户更改了某些设置之后),两个图形都占用相同的画布。
我要寻找的是:我需要完全摆脱旧图形,因此新图形是画布中唯一的图形。
这是一个简化的用例jsfiddle: http : //jsfiddle.net/XPAqX/
// make a new graph
var graph = new Springy.Graph();
// make some nodes
var spruce = graph.newNode({label: 'Norway Spruce'});
var fir = graph.newNode({label: 'Sicilian Fir'});
// connect them with an edge
graph.newEdge(spruce, fir);
$('#my_canvas').springy({ graph: graph, nodeSelected: function(node) {
alert(node.data.label);
} });
//now, I let the user update the dataset with ajax and re-render the graph.
graph = null;
graph = new Springy.Graph();
// make some nodes
var kittens = graph.newNode({label: 'Furry Baby Cats'});
var puppies = graph.newNode({label: 'Fluffy Baby Dogs'});
// connect them with an edge
graph.newEdge(kittens,puppies);
$('#my_canvas').springy({ graph: graph });
快速说明:在Springy github上作为问题交叉发布,但尚无答案: https : //github.com/dhotson/springy/issues/47
Springy Graph对象有点误导。 如果您查看源代码,您将看到它只是整个Springy上下文对象(符号)的访问层,该访问层实际上包含您的节点,因此addNode
不会将节点添加到Graph对象,而不会添加到Singleton Springy上下文对象。
您必须先使用removeNode
删除旧节点,就像我在这里所做的那样。
为了使事情更清楚:是的,Graph对象确实包含节点列表,但这些列表已传递给渲染器,并且渲染器是您“ springyfy”的每个画布DOM节点的单个实例。 更改Graph实例不会重置渲染器的内部上下文。
一个更复杂的解决方案是修改SpringyUI (jQuery插件)代码并处理用于重置内部渲染器的$('#canvas')。springy('reset')方法。 查看SpringyUI代码,我可以说这并不容易。
编辑:(删除了我所有的错误资料)
获得可行的解决方案:
向springyui.js添加以下清除函数之一
this.clear = function(){
for(var i=graph.nodes.length-1;i>=0;i--){
graph.removeNode(graph.nodes[i]);
}
}
要么
this.clear = function(){
graph.nodeSet = {};
graph.nodes = [];
graph.edges = [];
graph.adjacency = {};
graph.notify();
}
像这样使用它:
初始:
//don't call this twice!!
var graph = new Springy.Graph();
var springy=jQuery('#yourcanvas').springy({graph: graph});
工作流程:
function makeGraph(){
springy.clear();
//generate your graph hear
graph.addNodes(...)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.