I know you would typically use the pythagoras theorem to get the distance between points, but a circle doesn't have a x1 and x2. Here's an example. Without these values how can I calculate the distances?
circle {
fill: orange;
}
<svg transform="translate(0, 22)">
<circle class="point" cx="121.78235294117647" cy="13.200000000000001" r="3.1058823529411765" stroke="rgb(0, 0, 0)" stroke-width="1" data-values="[0.047]"></circle>
<circle class="point" cx="125.2764705882353" cy="30.28235294117647" r="3.1058823529411765" stroke="rgb(0, 0, 0)" stroke-width="1" data-values="[0.042]"></circle>
<circle class="point" cx="112.8529411764706" cy="30.67058823529412" r="3.1058823529411765" stroke="rgb(0, 0, 0)" stroke-width="1" data-values="[0.037]"></circle>
<circle class="point" cx="103.53529411764706" cy="32.22352941176471" r="3.1058823529411765" stroke="rgb(0, 0, 0)" stroke-width="1" data-values="[0.047]">
</svg>
The distance between two circles is equal to the distance of their centers minus the sum of their radii.
function distanceOfPoints(p0, p1) {
let dx = p0.x - p1.x;
let dy = p0.y - p1.y;
return Math.sqrt(dx*dx + dy*dy);
}
function distanceOfCircles(cen0, rad0, cen1, rad1) {
// if the circles intersect, our distance might be negative
return Math.max(0, distanceOfPoints(cen0, cen1) - rad0 - rad1);
}
In the SVG, cx and cy are the centers of the circle (cen0, cen1) and r is their radius (rad0, rad1).
To obtain the minimum distance between ALL circles, you can loop through all pairs of circles and update your result-distance whenever you find a lower one.
To calculate the minimum distance between two circles, you first take a vector that connects the two circle centers and calculate its length. Afterwards, you subtract the radii of both circles because the closest points of both circles must be away from the circle center exactly in the distance of each radius.
Edit: The horizontal and vertical distance values do not have to be positive because they will be squared in the next step anyhow (thanks to @Jan Schultke for the advice).
const circle1 = {
x: 13, // horizontal center coordinate
y: 4, // vertical center coordinate
radius: 5
};
const circle2 = {
x: 9, // horizontal center coordinate
y: 24, // vertical center coordinate
radius: 3
};
function minimumDistance(circle1, circle2) {
const horizontalDistance = circle1.x - circle2.x;
const verticalDistance = circle1.y - circle2.y;
const distanceBetweenCenter = Math.sqrt(horizontalDistance**2 + verticalDistance**2); // pythagoras
return distanceBetweenCenter - circle1.radius - circle2.radius;
}
console.log(minimumDistance(circle1, circle2));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With