[英]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.