How to determine if a circle is inside a circle using Paper.js?

59 Views Asked by At

How can one determine if a circle is inside another circle? I thought I had it figured out using isInside method.

Note: This code will run on http://sketch.paperjs.org

Expect Circle2 to be inside Circle1

var circle1 = new Path.Circle(new Point(100, 100), 100);
var circle2 = new Path.Circle(new Point(100, 100), 50);

circle1.strokeWidth = 2;
circle1.strokeColor = "black";
circle1.fillColor = "blue";
circle2.strokeWidth = 2;
circle2.strokeColor = "black";
circle2.fillColor = "green";

console.log(circle1.isInside(circle2));
console.log(circle2.isInside(circle1));

Outputs:

false false

2

There are 2 best solutions below

0
JasonC On

From the docs isInside requires a rectangle object to be passed in as a parameter, not a path.

Working Code

var circle1 = new Path.Circle(new Point(100, 100), 100);
var circle2 = new Path.Circle(new Point(100, 100), 50);

circle1.strokeWidth = 2;
circle1.strokeColor = "black";
circle1.fillColor = "blue";
circle2.strokeWidth = 2;
circle2.strokeColor = "black";
circle2.fillColor = "green";

console.log(circle1.isInside(circle2.bounds));
console.log(circle2.isInside(circle1.bounds));

Outputs:

false true

1
Ripi2 On

To know if circle_small with radius Rs is enterely inside circle_big with radius Rb just check that the distance between their centers (Cb, Cs) is less than Rb-Rs.
If you allow both circles "touch" in one point then the condition is less or equal to Rb-Rs.

General case:

var discen = Math.sqrt( (Cb_x - Cs_x)*(Cb_x - Cs_x) + (Cb_y - Cs_y)*(Cb_y - Cs_y) );
var radiff = Rb - Rs;
if (discen < radiff)
    //circle_small fully inside circle_big, no touching point
else if ( Math.abs(discen-radiff) < 0.0001 ) //better that discen==radiff
    //circle_small fully inside circle_big, one tangent common (touching point)
else if (discen < Rb+Rs)
    //Both circles intersect, partially one inside the other
else if ( Math.abs(discen-Rb-Rs) < 0.0001 )
    //Circles are exterior, but they contact at one point (they're tangent to each other)
else
    //Not intersecting circles

Note:
About the "better than a==b" thing, it's for the case where a or b are not integers. For floats some digits likely get lost: See Is floating point math broken?

Comparing a-b, in absolute value, with some small thereshold make the comparison valid.