D3.js Dynamic Connector Between Objects

I am very new to JS and D3 and I searched for that ton but found only examples that are too advanced.

I am making a simple solution graph and I am getting stuck trying to connect 2 nodes using a line / path. Objects can be moved with the mouse, and the path should always be updated to reflect the position of the objects.

This is my basic source of knowledge: https://github.com/mbostock/d3/wiki/SVG-Shapes , but I don’t quite understand how to do something smart with it.

Here is what I still have: http://jsbin.com/AXEFERo/5/edit

You don’t need fancy things, you just need to understand how to create connectors and dynamically update them when objects are dragged. Thank you very much!

+6
source share
1 answer

To draw a line between the circles, you do not 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 a dynamic position is a bit more complicated. At the moment, you have no way to distinguish which of the circles is dragging. One way to do this is to add a difference class to the g elements.

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

and similarly for another. Now you can include the class in your dragmove function and update the start or 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); } 

Fill in the example here . There are other, more elegant ways to achieve this. In a real application, you will have data attached to the elements, and they can use them to distinguish between different circles.

+6
source

Source: https://habr.com/ru/post/953382/


All Articles