Placing canvas circles in a circular manner without overlapping

I need to draw a conceptual map of circles with the same radius, as soon as it is clicked, it should show its children, and these children should not intersect each other. I can divide the entire circular position by Math.PI*2/required_length_of_children . and taking positions with

  var new_left=Math.round(origin.x+radius*Math.cos(angle)); var new_top=Math.round(origin.y+radius*Math.sin(angle)); 

Now my problem is how to find out the angle that has available space and draw it. mostly looking for a hyperbolic tree-like arrangement of circles. Thanks in advance for your help.

+5
source share
1 answer

If you think about it when the circle is centered on the edge of another circle, the triangle between two centers and one intersection point has all the known edges: R, R and r (where R is a large radius and r is small). We can use some math to find the angle in the center of the big circle for this:

https://www.mathsisfun.com/algebra/trig-solving-sss-triangles.html

Then we can double it so that the angle takes into account the entire width of the small circle on the edge, and the formula as a result looks like this: 2*Math.acos(1 - (r**2)/(2*R**2))

Now, to make sure that this math is correct, we can draw on the canvas so that the circles located at this angle do not overlap:

 function testShape(middleX, middleY, R, r, n) { var i, angle = 0; var inc = 2*Math.acos(1 - (r**2)/(2*R**2)); circle(middleX, middleY, "blue", R); for (i = 0; i < n; i++) { circle(middleX+Math.cos(angle)*R, middleY+Math.sin(angle)*R, "red", r); angle += inc; } } 

https://jsfiddle.net/snydergd/rh6jcf30/7/

0
source

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


All Articles