简体   繁体   English

D3.js对象之间的动态连接器

[英]D3.js Dynamic connector between objects

I'm very new to both JS and D3, and I've googled this a tonne but only found examples that are a bit too advanced. 我对JS和D3都很陌生,我用谷歌搜索了这一吨,但只发现了一些有点过于先进的例子。

I'm making a simple decision graph implementation, and I'm stuck trying to connect 2 nodes with a line / path. 我正在做一个简单的决策图实现,而我却试图用线/路径连接2个节点。 The objects can be moved around with the mouse, and the path should always update to reflect the positions of the objects. 可以使用鼠标移动对象,并且路径应始终更新以反映对象的位置。

This is my base source of knowledge: https://github.com/mbostock/d3/wiki/SVG-Shapes , but I don't quite understand how to do something smart with it. 这是我的基础知识来源: https//github.com/mbostock/d3/wiki/SVG-Shapes ,但我不太明白如何用它做一些聪明的事情。

Here is what I have so far: http://jsbin.com/AXEFERo/5/edit 以下是我到目前为止: http//jsbin.com/AXEFERo/5/edit

Don't need the fancy stuff, just need to understand how to create connectors and have them update dynamically when the objects are being dragged around. 不需要花哨的东西,只需要了解如何创建连接器并让它们在拖动对象时动态更新。 Big thanks! 十分感谢!

To draw a line between the circles, you don't need anything special -- just the line element. 要在圆之间画一条线,你不需要任何特殊的东西 - 只需要line元素。

var line = svg.append("line")
        .style("stroke", "black")
        .attr("x1", 150)
        .attr("y1", 100)
        .attr("x2", 250)
        .attr("y2", 300);

Updating the position dynamically is a bit more difficult. 动态更新位置有点困难。 At the moment, you have no means of distinguishing which of the circles is being dragged. 目前,您无法区分哪些圈子被拖动。 One way of doing this is to add a distinguishing class to the g elements. 这样做的一种方法是为g元素添加一个区别类。

var g1 = svg.append("g")
        .attr("transform", "translate(" + 150 + "," + 100 + ")")
        .attr("class", "first")
        ...

and similarly for the other one. 和另一个相似。 Now you can switch on the class in your dragmove function and update either the start or the end coordinates of the line. 现在,您可以在dragmove函数中打开类,并更新该行的开始或结束坐标。

if(d3.select(this).attr("class") == "first") {
            line.attr("x1", x);
            line.attr("y1", y);
} else {
            line.attr("x2", x);
            line.attr("y2", y);
}

Complete example here . 在这里完成示例。 There are other, more elegant ways of achieving this. 还有其他更优雅的方法来实现这一目标。 In a real application, you would have data bound to the elements and could use that to distinguish between the different circles. 在实际应用程序中,您将拥有绑定到元素的数据,并可以使用它来区分不同的圆圈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM