【问题标题】:Freezing force directed network graph and make draggable in D3冻结力定向网络图并在 D3 中实现可拖动
【发布时间】:2013-01-12 18:05:06
【问题描述】:

我正在尝试完全冻结 d3 中的强制定向网络!我尝试将摩擦值设置为 0,但网络变得更加紧凑,节点仍然略微悬停。

var force = d3.layout.force()
.charge(-220)
.linkDistance(70)
.friction(0);

我还希望我的节点是可拖动的,即当它们被拖动时移动位置。

最终,我试图获得类似于 Cytoscape js 的东西,看起来像 this

谢谢!

【问题讨论】:

    标签: javascript d3.js force-layout


    【解决方案1】:

    首先如果你想在某个时间“冻结”图形,可以使用force布局的stop命令:

    force.stop()
    

    一个很好的用途是首先让图形自组织(使用tick)然后停止强制:

    // include in beginning of script
    force.start();
    for (var i = 0; i < n; ++i) force.tick();
    force.stop();
    

    然后,如果您想拖放节点,一个好主意是在 d3 示例页面上搜索 drag,您会找到以下链接:Drag and Drop Support to set nodes to fixed position when dropped,其中包含您想要的一切。顺便说一句,它也与你可能会感兴趣的一个 stackoverflow 问题有关:D3 force directed graph with drag and drop support to make selected node position fixed when dropped

    这是用于拖放的有趣代码,适用于力已停止的图形(我只是注释了一些行,但不确定,因此请通过取消注释来验证它是否按预期工作)

    var node_drag = d3.behavior.drag()
        .on("dragstart", dragstart)
        .on("drag", dragmove)
        .on("dragend", dragend);
    
    function dragstart(d, i) {
        //force.stop() // stops the force auto positioning before you start dragging
    }
    
    function dragmove(d, i) {
        d.px += d3.event.dx;
        d.py += d3.event.dy;
        d.x += d3.event.dx;
        d.y += d3.event.dy; 
        tick(); // this is the key to make it work together with updating both px,py,x,y on d !
    }
    
    function dragend(d, i) {
        //d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        //tick();
        //force.resume();
    }
    
    function tick() {
      link.attr("x1", function(d) { return d.source.x; })
          .attr("y1", function(d) { return d.source.y; })
          .attr("x2", function(d) { return d.target.x; })
          .attr("y2", function(d) { return d.target.y; });
    
      node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
    };
    

    【讨论】:

      猜你喜欢
      • 2015-03-22
      • 2014-12-05
      • 2017-08-30
      • 2012-02-19
      • 1970-01-01
      • 2014-03-06
      • 2019-08-10
      • 1970-01-01
      • 2020-12-23
      相关资源
      最近更新 更多