javascript D3.js 对象之间的动态连接器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18672761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
D3.js Dynamic connector between objects
提问by babyjet
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. The objects can be moved around with the mouse, and the path should always update to reflect the positions of the objects.
我正在制作一个简单的决策图实现,但我一直在尝试用一条线/路径连接 2 个节点。可以使用鼠标移动对象,并且路径应始终更新以反映对象的位置。
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!
不需要花哨的东西,只需要了解如何创建连接器并在拖动对象时动态更新它们。太谢谢了!
回答by Lars Kotthoff
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.
完整的例子在这里。还有其他更优雅的方法可以实现这一点。在实际应用程序中,您会将数据绑定到元素,并可以使用它来区分不同的圆圈。