D3.js对象之间的动态连接器 [英] D3.js Dynamic connector between objects

查看:101
本文介绍了D3.js对象之间的动态连接器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JS和D3都很新,而且我用谷歌搜索了这一吨,但只发现了一些有点太高级的例子。

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.

我'我做了一个简单的决策图实现,我试图用线/路径连接2个节点。可以使用鼠标移动对象,并且路径应始终更新以反映对象的位置。

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.

这是我的基本知识来源: https:/ /github.com/mbostock/d3/wiki/SVG-Shapes ,但我不太明白如何用它做一些聪明的事。

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.

这里是我到目前为止: http://jsbin.com/AXEFERo/5/edit

Here is what I have so far: 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.

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

动态更新头寸有点困难。目前,您无法区分哪些圈子被拖动。一种方法是在 g 元素中添加一个区别类。

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.

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

和另一个类似。现在,您可以在 dragmove 函数中打开该类,并更新该行的开始或结束坐标。

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.

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.

这篇关于D3.js对象之间的动态连接器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆