iTranslated by AI
Developing a Tournament-Style Linear Tree UI with D3.js
Previously, I developed a hierarchical UI using the D3.js hierarchy API.
In the previous article, parent and child nodes were connected by curved lines, but this time, I want to connect them using polyline (broken line) segments.
For details on developing a hierarchical UI using hierarchy, please see the following article:
Now, let's explain the mechanism for drawing a linear tree.
Getting Node Positions
Since we will be drawing lines with SVG this time, we need to get the coordinate positions to pass to the path property.
Chain methods via the D3 API receive node information as an argument, so we can retrieve the node's coordinate positions from there.
.attr("d", d => { /** d = node object **/ })
The target node's coordinate positions are obtained via d.x and d.y.
Creation of the square gray nodes is omitted here.
The node position held by the node object (target node = "晴れ" (Sunny)) is the red circle below.

We will draw the linear segments relative to the x and y of the red circle above to connect to the parent node.
Getting Parent Node Positions
The parent node's coordinate position is obtained using d.parent.x and d.parent.y.
The node position of the parent node is the blue circle below.

Setting Drawing Positions in the path Property
To draw a polyline, four points are required in this case. We will obtain the locations of the green circles below and set them in the path property.
Assume the node width is 140px and the height is 60px.

.attr("d", d => `M${Point A} L${Point B} ${Point C} ${Point D}`);
.attr(
"d",
(d) => `
M${d.x + 140 / 2}, ${d.y} // Point A
L${d.x + 140 / 2}, ${d.y - 30} // Point B
${d.parent.x + 140 / 2}, ${d.y - 30} // Point C
${d.parent.x + 140 / 2}, ${d.parent.y + 60} // Point D
`
);
With that, a linear tree where parent and child nodes are connected by polylines is created.
If you would like to see the full source code, please check out the demo below.
Discussion