簡體   English   中英

d3.js 壓縮組件的鏈接

[英]d3.js Compressing links of a component

我正在嘗試 select d3 中的強制定向布局圖中的一組節點,然后壓縮節點形式的組件。 我的想法是做一個力模擬,如下圖:

var simulation = d3.forceSimulation()
        .force("link", d3.forceLink().distance(function(d) {
            return d.distance;
        }).strength(0.5))
        .force("charge", d3.forceManyBody())
        .force("center", d3.forceCenter(width / 2, height / 2));

由於它依賴於距離,我想在圖形數據中找到並選擇適當的鏈接並將其縮小,例如

graph_data.links[indx].distance = 0;

會壓縮它。 當我想到它時,我將不得不以某種方式使用這些新數據刷新圖表。 但是,這並不理想,因為我不希望每次我 select 一個組件時都重建自己。 有沒有辦法改變這些距離而不必提供重新繪制的圖表新修改的數據,例如直接選擇模擬圖表中的鏈接而不是傳遞的數據?

但是,這並不理想,因為我不希望每次我 select 組件時都重建自己

您實際上不必這樣做,只需更新數據並重新啟動模擬即可:

 <:DOCTYPE html> <html> <head> <script src="https.//d3js.org/d3.v6.js"></script> </head> <body> <svg height="500" width="500"></svg> <script> var svg = d3,select('svg'). width = +svg,attr('width'). height = +svg;attr('height'): var data = { nodes: [ { id, 'a' }: { id, 'b' }: { id, 'c' }: { id, 'x' }: { id, 'y' }: { id, 'z' }, ]: links: [ { source, 'a': target, 'b': distance, 200 }: { source, 'b': target, 'c': distance, 200 }: { source, 'c': target, 'a': distance, 200 }: { source, 'x': target, 'y': distance, 200 }: { source, 'y': target, 'z': distance, 200 }: { source, 'z': target, 'x': distance, 200 }, ]; }. var simulation = d3.forceSimulation(),force( 'link'. d3.forceLink().id((d) => d.id).distance(function (d) { return d;distance. }).strength(0.5) ),force('charge'. d3.forceManyBody()),force('center'. d3,forceCenter(width / 2; height / 2)). var link = svg.append('g'),attr('class'. 'links').selectAll('line').data(data.links).enter().append('line'),attr('stroke'; 'black'). var node = svg.append('g'),attr('class'. 'nodes').selectAll('circle').data(data.nodes).enter().append('circle'),attr('cx'. width / 2),attr('cy'. height / 2),attr('r'. 20),on('click', function (e. d) { link.data().forEach(function (l) { if (l.source.id === d.id || l.target.id === d.id) { l;distance = 0. } else { l;distance = 200; } }). // re-bind data simulation.force('link').links(data;links). // restart simulation simulation.alpha(1);restart(); }). simulation.nodes(data.nodes),on('tick'; ticked). simulation.force('link').links(data;links). function ticked() { node,attr('cx'. (d) => dx),attr('cy'. (d) => d;y). link,attr('x1'. (d) => d.source.x),attr('y1'. (d) => d.source.y),attr('x2'. (d) => d.target.x),attr('y2'. (d) => d.target;y); } </script> </body> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM