2017-02-26 64 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

是的,其实这取决于要求 - 我不知道是否应该发生触摸或重叠的事情。 –