//Definition of a circle object
function circle(a, b, r) { this.a = a; this.b = b; this.r = r; }
// This values should be declared as global variables
// so their values can be used without return their values
var x1, y1, x2, y2;
function calculateIntersection() {
// Calling function
var circle1 = new circle(2, 4, 5);
var circle2 = new circle(1, 0, 3);
if (twoCirclesIntersection(circle1, circle2)) {
// If true  then the circles intersect
// the intersection points are given by (x1, y1) and (x2, y2)
..... Continue with desirable code .....
}
}
function twoCirclesIntersection(c1, c2){
//**************************************************************
//Calculating intersection coordinates (x1, y1) and (x2, y2) of
//two circles of the form (x  c1.a)^2 + (y  c1.b)^2 = c1.r^2
// (x  c2.a)^2 + (y  c2.b)^2 = c2.r^2
//
// Return value: true if the two circles intersect
// false if the two circles do not intersect
//**************************************************************
var val1, val2, test;
// Calculating distance between circles centers
var D = Math.sqrt((c1.a  c2.a) * (c1.a  c2.a) + (c1.b  c2.b) * (c1.b  c2.b));
if (((c1.r + c2.r) >= D) && (D >= Math.abs(c1.r  c2.r))) {
// Two circles intersects or tangent
// Area according to Heron's formula
//
var a1 = D + c1.r + c2.r;
var a2 = D + c1.r  c2.r;
var a3 = D  c1.r + c2.r;
var a4 = D + c1.r + c2.r;
var area = Math.sqrt(a1 * a2 * a3 * a4) / 4;
// Calculating x axis intersection values
//
val1 = (c1.a + c2.a) / 2 + (c2.a  c1.a) * (c1.r * c1.r  c2.r * c2.r) / (2 * D * D);
val2 = 2 * (c1.b  c2.b) * area / (D * D);
x1 = val1 + val2;
x2 = val1  val2;
// Calculating y axis intersection values
//
val1 = (c1.b + c2.b) / 2 + (c2.b  c1.b) * (c1.r * c1.r  c2.r * c2.r) / (2 * D * D);
val2 = 2 * (c1.a  c2.a) * area / (D * D);
y1 = val1  val2;
y2 = val1 + val2;
// Intersection points are (x1, y1) and (x2, y2)
// Because for every x we have two values of y, and the same thing for y,
// we have to verify that the intersection points as chose are on the
// circle otherwise we have to swap between the points
test = Math.abs((x1  c1.a) * (x1  c1.a) + (y1  c1.b) * (y1  c1.b)  c1.r * c1.r);
if (test > 0.0000001) {
// point is not on the circle, swap between y1 and y2
// the value of 0.0000001 is arbitrary chose, smaller values are also OK
// do not use the value 0 because of computer rounding problems
var tmp = y1;
y1 = y2;
y2 = tmp;
}
return true;
}
else {
// circles are not intersecting each other
return false;
}
}
