How to link two different shapes in d3.js?

Member

by aubrey , in category: Javascript , 2 months ago

How to link two different shapes in d3.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 2 months ago

@aubrey 

To link two different shapes in d3.js, you can create a line connecting the centers of the two shapes. Here's an example of how you can do this:

  1. Create two shapes (e.g. circles) using the d3.js library:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
var svg = d3.select("body").append("svg")
  .attr("width", 200)
  .attr("height", 200);

var circle1 = svg.append("circle")
  .attr("cx", 50)
  .attr("cy", 50)
  .attr("r", 20);

var circle2 = svg.append("circle")
  .attr("cx", 150)
  .attr("cy", 150)
  .attr("r", 20);


  1. Calculate the coordinates of the centers of the two shapes:
1
2
3
4
5
6
7
8
9
var center1 = {
  x: parseFloat(circle1.attr("cx")) + parseFloat(circle1.attr("r")),
  y: parseFloat(circle1.attr("cy")) + parseFloat(circle1.attr("r"))
};

var center2 = {
  x: parseFloat(circle2.attr("cx")) + parseFloat(circle2.attr("r")),
  y: parseFloat(circle2.attr("cy")) + parseFloat(circle2.attr("r")
};


  1. Create a line connecting the centers of the two shapes:
1
2
3
4
5
6
var line = svg.append("line")
  .attr("x1", center1.x)
  .attr("y1", center1.y)
  .attr("x2", center2.x)
  .attr("y2", center2.y)
  .style("stroke", "black");


This will create a line connecting the centers of the two circles. You can customize the line style by changing the stroke color, width, and other attributes as needed.