![](/img/trans.png)
[英]Manually Add Nodes to JavaScript InfoVis Toolkit Force Directed Graph
[英]How to hide and restore custom nodes in InfoVis/JIT force directed graph?
我正在嘗試使用InfoVis / JIT來繪制力圖,以可視化網絡。 我是Java腳本和JIT的新手。 我已經在js文件中使用以下代碼創建了自己的自定義節點類型,這使我可以在節點上顯示圖像。
$jit.ForceDirected.Plot.NodeTypes.implement({
'icon1': {
'render': function(node, canvas){
var ctx = canvas.getCtx();
var img = new Image();
img.src='magnify.png';
var pos = node.pos.getc(true);
img.onload = function() {
ctx.drawImage(img, pos.x, pos.y);
};
},
'contains': function(node,pos){
var npos = node.pos.getc(true);
dim = node.getData('dim');
return this.nodeHelper.circle.contains(npos, pos, dim);
//return this.nodeHelper.square.contains(npos, pos, dim);
}
}
我使用json數據對象中的“ $ type”:“ icon1”將此自定義節點類型分配給節點。 我確實在該節點上獲得了圖像,但是問題是我無法在需要時將其隱藏。 我可以使用以下代碼隱藏諸如圓形,正方形等內置節點類型。
node.setData('alpha', 0);
node.eachAdjacency(function(adj) {
adj.setData('alpha', 0);
});
fd.fx.animate({
modes: ['node-property:alpha',
'edge-property:alpha'],
duration: 2000
});
但是相同的代碼不適用於自定義節點。 因此,我嘗試將節點類型臨時更改為內置的“圓形”類型,將其隱藏,然后將節點類型重新設置為其原始設置,即我的自定義節點icon1。
function hideNode( ){
var typeOfNode = node.getData('type');
node.setData( 'type','circle');
node.setData('alpha', 0);
node.eachAdjacency(function(adj) {
adj.setData('alpha', 0);
});
fd.fx.animate({
modes: ['node-property:alpha',
'edge-property:alpha'],
duration: 2000
});
node.setData('type',typeOfNode );
}
我認為這應該可行,但是自定義圖像會在畫布上恢復一段時間。 如果我沒有將節點的類型重置為原始類型,即在上面的代碼中並注釋掉以下語句並調用hide函數,則該節點將被隱藏。
node.setData('type',typeOfNode );
我無法弄清楚如何僅通過將節點的類型設置為某些自定義類型來呈現節點。 任何有關此問題的幫助將不勝感激。
我需要將節點的類型重置為其原始類型,因為我希望在需要時通過調用unhide函數來還原該節點。 如果我不將節點的類型重置為原始類型,則還原后它將被渲染為圓形。
我已經通過了API和Google即時搜索小組,但找不到答案。 有人可以幫忙嗎?
這是Plot的plotNode函數的一個片段:
var alpha = node.getData('alpha'),
ctx = canvas.getCtx();
ctx.save();
ctx.globalAlpha = alpha;
// snip
this.nodeTypes[f].render.call(this, node, canvas, animating);
ctx.restore();
如您所見,在調用節點的render函數之前,將節點的alpha值立即應用於畫布。 渲染節點后,畫布將還原到先前的狀態。
這里的問題是您的自定義節點的render
函數不會同步呈現該節點,並且在調用drawImage
之前將恢復畫布狀態。 因此,您可以執行以下兩項操作之一:
1)預加載並緩存圖像(首選方法,因為這也可以防止圖像閃爍並有助於提高性能):
// preload image
var magnifyImg = new Image();
magnifyImg.src = 'magnify.png';
// 'icon1' node render function:
'render': function(node, canvas){
var ctx = canvas.getCtx();
var pos = node.pos.getc(true);
ctx.drawImage(magnifyImg, pos.x, pos.y);
}
或2)保存畫布狀態,重新應用Alpha,然后在onload
處理程序中繪制圖像后恢復畫布狀態:
// 'icon1' node render function:
'render': function(node, canvas){
var ctx = canvas.getCtx();
var img = new Image();
img.src='magnify.png';
var pos = node.pos.getc(true);
img.onload = function() {
ctx.save(); // save current canvas state
ctx.globalAlpha = node.getData('alpha'); // apply node alpha
ctx.drawImage(img, pos.x, pos.y); // draw image
ctx.restore(); // revert to previous canvas state
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.