D3.js Dynamic connector between objects

こ雲淡風輕ζ 提交于 2019-12-01 04:14:54

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);

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")
        ...

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!