2015-09-07 136 views
0

基本上,我想要做的是要合并这两个例子:D3.js力布局拖/缩放/平移和连接节点的能力

http://bl.ocks.org/mbostock/6123708

http://bl.ocks.org/benzguo/4370043

我想使用一个按键来选择,如果我想将一个节点,或者画一条线,像这样:

function dragstarted(d) { 
    d3.event.sourceEvent.stopPropagation(); 

    if (d3.event.sourceEvent.ctrlKey) { 
     // drag a line 
    } else { 
     // drag the node 
    } 
} 

的dragstarted函数被调用于dragstart事件。在这种情况下,我应该停止此节点的拖动事件,但我不知道如何。我试过打电话

d3.select(this).on('.drag', null); 

没有结果。

另一种选择是订阅每个节点到mousedown.drag使用此项功能:

function dragDecisor(d) { 
    if (d3.event.ctrlKey) { 
     console.log('Draw a line...'); 
    } else { 
     console.log('Drag a node...'); 
    } 
} 

但后来我需要让拖动事件传播,而且似乎还没有一个明确的方式来做到这一点。我试图创建一个事件,如mbostock(我不能发布更多链接,请参阅d3 issue#100)解释。

有什么建议吗?

回答

0

我现在可以按住ctrl拖动一个节点。

我标志着一个叫ctrlPressed

function mousedown() { 
    if (!mousedown_node && !mousedown_link) { 
    // allow panning if nothing is selected 
    vis.call(d3.behavior.zoom().on("zoom"), rescale); 
    return; 
    } 
    //marking the ctrlKey press flag 
    if(d3.event.ctrlKey){ 
     ctrlPressed = true; 
    } else { 
     ctrlPressed = false; 
    } 
} 

标志,那么在鼠标移动我加了条件,使和更新行,如果按下CTRL键

function mousemove() { 
    if (!mousedown_node) return; 
    if(!d3.event.ctrlKey){ 
     // update drag line 
    drag_line 
     .attr("x1", mousedown_node.x) 
     .attr("y1", mousedown_node.y) 
     .attr("x2", d3.svg.mouse(this)[0]) 
     .attr("y2", d3.svg.mouse(this)[1]); 
    } else { 
    mousedown_node.x = d3.svg.mouse(this)[0]; 
    mousedown_node.y = d3.svg.mouse(this)[1]; 
    } 

} 

我的工作小提琴here

希望这可以帮助你!

+0

酷!我没有意识到第二个例子是使用d3 v2。随着v3我遇到一些问题,因为它似乎我不能使用vis对象上的调用函数。你知道如何解决这个问题吗? –

+0

是啊真正的V3有一些问题,超出了我的修复:) – Cyril