2012-08-31 36 views
15

enter image description hereJavaScript函數返回兩個圓之間的x,y交點?

我得到了兩個圓的(x,y)中心位置及其半徑,但我需要使用JavaScript找到它們的交點(用紅色標記)。

對於數學而言,我認爲最好的解釋是here(兩個圓的交點),但是我並不真正理解數學,所以我無法實現它。

例如d = || P1-P0 || ,||是什麼?代表?這是否意味着結果數字總是正面的?

而且P2 = P0 + a(P1-P0)/ d,這裏的P不是這樣的(10,50)?但是在JavaScript中使用(10,50)+13會給你63,所以它只是忽略了第一個數字,所以會發生什麼?結果應該是(23,63)還是?還有P1-P0部分或(40,30) - (10,60),你如何在JavaScript中表達?

+2

這些矢量的功能;畢竟,你在兩個維度上運作。你需要在JS中構造等價的向量代數函數來獲得你想要的結果。 – Xophmeister

+2

...或將底部鏈接的C實現轉換爲JavaScript。 – duskwuff

+2

'd = || P1-P0 ||'代表點P0和P1之間的距離,所以d = sqrt((x1-x2)2 +(y1-y2)2) –

回答

31

翻譯該網站上的C函數爲JavaScript:

function intersection(x0, y0, r0, x1, y1, r1) { 
     var a, dx, dy, d, h, rx, ry; 
     var x2, y2; 

     /* dx and dy are the vertical and horizontal distances between 
     * the circle centers. 
     */ 
     dx = x1 - x0; 
     dy = y1 - y0; 

     /* Determine the straight-line distance between the centers. */ 
     d = Math.sqrt((dy*dy) + (dx*dx)); 

     /* Check for solvability. */ 
     if (d > (r0 + r1)) { 
      /* no solution. circles do not intersect. */ 
      return false; 
     } 
     if (d < Math.abs(r0 - r1)) { 
      /* no solution. one circle is contained in the other */ 
      return false; 
     } 

     /* 'point 2' is the point where the line through the circle 
     * intersection points crosses the line between the circle 
     * centers. 
     */ 

     /* Determine the distance from point 0 to point 2. */ 
     a = ((r0*r0) - (r1*r1) + (d*d))/(2.0 * d) ; 

     /* Determine the coordinates of point 2. */ 
     x2 = x0 + (dx * a/d); 
     y2 = y0 + (dy * a/d); 

     /* Determine the distance from point 2 to either of the 
     * intersection points. 
     */ 
     h = Math.sqrt((r0*r0) - (a*a)); 

     /* Now determine the offsets of the intersection points from 
     * point 2. 
     */ 
     rx = -dy * (h/d); 
     ry = dx * (h/d); 

     /* Determine the absolute intersection points. */ 
     var xi = x2 + rx; 
     var xi_prime = x2 - rx; 
     var yi = y2 + ry; 
     var yi_prime = y2 - ry; 

     return [xi, xi_prime, yi, yi_prime]; 
    } 
+0

從ES6開始,'Math.hypot(dx,dy)'可以用來代替'Math.sqrt((dy * dy)+(dx * dx))''。 – Arnauld

相關問題