2017-02-26 68 views
2

我寫了這個函數來檢查兩個重疊元素
(它們是矩形的),
如下面的第一張圖所示。使用javascript檢查重疊圓形元素的函數?

問題是,我想使用圓形elelemts, 如下面的第二張圖所示。

所以我想我需要添加一些Math.PI和半徑計算, 希望得到任何幫助......


          
  
 var checkOverlap = function (a, b) { 
 
      if (
 
       ((a.left < b.left && a.left + a.width > b.left) || 
 
       (a.left > b.left && a.left + a.width < b.left + b.width) || 
 
       (a.left > b.left && a.left + a.width > b.left + b.width)) && 
 
       ((a.top < b.top && a.top + a.height > b.top) || 
 
       (a.top > b.top && a.top + a.height > b.top) || 
 
       (a.top > b.top && a.top < b.top + b.height)) && 
 
       (a.left < b.left + b.width) && 
 
       (a.top < b.top + b.height) 
 
      ) { 
 
       return true; 
 
      } 
 
     };

enter image description here enter image description here

回答

2

兩個圓盤相交,當且僅當的距離在他們的中心之間不超過他們的半徑之和。

如果一個平面上兩個點的座標是(x1, y1)(x2, y2),它們之間的距離是(x1 - x2)^2 + (y1 - y2)^2的平方根。

你應該可以從這裏拿起它。

+0

正確的金錢,謝謝。 –

1

檢查圓圈是否重疊比用矩形進行類似檢查更容易。

假設你不處理省略號,你只需要計算,如果其中心(Pythagoras theorem)之間的距離小於其半徑的總和:

// long argument names to be more descriptive 

function checkIfCirclesOverlap(circle1CenterX, circle1CenterY, circle1Radius, circle2CenterX, circle2CenterY, circle2Radius) { 
    const xDistance = circle1CenterX - circle2CenterX; 
    const yDistance = circle1CenterY - circle2CenterY; 
    const distance = Math.sqrt(xDistance * xDistance + yDistance * yDistance); 
    return distance < circle1Radius + circle2Radius; 
} 
+0

它可能應該少於或等於*。如果距離等於半徑的總和,則仍然有一個交點。 – avysk

+0

是的,其實這取決於要求 - 我不知道是否應該發生觸摸或重疊的事情。 –