Reputation: 518
I got a mathematical problem for designing icons, and I am looking for a JavaScript solution.
I take 2 circles, each a different radius and position, and a point. I want to know the smallest circle that contains the two circles and goes along the point.
The red cirle is the circle I want to know
In want a function like this:
function calculate(c1x, c1y, c1r, c2x, c2y, c2r, px, py){
//Calculation
return {
x: outX,
y: outY,
r: outR
};
}
Upvotes: 2
Views: 146
Reputation: 80107
There is a lot of degenerate cases: one circle is inside another and so on.
For the most general case - big circle touches both small ones and goes through the point - we need to solve a system of three equations for three unknowns cx, cy, R
:
(px - cx)^2 + (py - cy)^2 = R^2
(cx1 - cx)^2 + (cy1 - cy)^2 = (R-r1)^2
(cx2 - cx)^2 + (cy2 - cy)^2 = (R-r2)^2
You can try to solve it with paper and pencil or use some program for symbolic calculations like Maple, Mathematica, Matlab, MathCad etc.
P.S. to slightly simplify calculations, subtract point coordinates from all values, solve system
cx^2 + cy^2 = R^2
(cx1' - cx)^2 + (cy1' - cy)^2 = (R-r1)^2
(cx2' - cx)^2 + (cy2' - cy)^2 = (R-r2)^2
and add px, py to the result
Upvotes: 5
Reputation: 780
function distance(x1, y1, x2, y2){
return Math.sqrt(Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2));
}
function calculate(c1x, c1y, c1r, c2x, c2y, c2r, px, py){
var dpc1 = distance(c1x, c1y, px, py) + c1r;
var dpc2 = distance(c2x, c2y, px, py) + c2r;
var dc1c2 = distance(c1x, c1y, c2x, c2y);
var theta = Math.acos((dpc1*dpc1 + dpc2*dpc2 - dc1c2*dc1c2)/(2*dpc1*dpc2))/2;
var outR = Math.max(dpc1, dpc2);
var outX = px + outR * Math.cos(theta);
var outY = py + outR * Math.sin(theta);
return {
x: outX,
y: outY,
r: outR
};
}
Upvotes: 1