1

In my code, I used Jquery UI to make the elements draggable for easy debugging. The code I wrote with the help of someone tells me if the rounded divs are overlapping each other but I want to check if a rounded div is overlapping a square div. How can I do that?

BTW If you remove the round class the div will become a square.

let $label = $('.overlap-label span');

const hasOverlap = (x0, y0, r0, x1, y1, r1) => {
  return Math.hypot(x0 - x1, y0 - y1) <= r0 + r1;
}
const coordinates = (className) => {
  const val = document.querySelector(className);
  const rect = val.getBoundingClientRect();
  return {
    y: rect.top + val.offsetHeight / 2,
    x: rect.left + val.offsetHeight / 2,
    rad: val.offsetHeight / 2
  }
}
const checkForOverlap = () => {
  const cm = coordinates(".circle.small");
  const cl = coordinates(".circle.large");
  $label.text(hasOverlap(cm.x, cm.y, cm.rad, cl.x, cl.y, document.querySelector(".circle.large").offsetHeight / 2));
}

$('.parent').draggable().on('drag', checkForOverlap);
.circle {
  width: var(--square);
  height: var(--square);
  background: var(--bg);
  display: inline-block;
}

.round {
  border-radius: 50%;
}

.parent {
  display: inline-block;
}

.small {
  --square: 50px;
  --bg: red;
}

.large {
  --square: 100px;
  --bg: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/themes/base/jquery-ui.min.css" />

<div class="overlap-label">Circles are overlapping? <span>false</span></div>
<div class="parent">
  <div class="circle small round"></div>
</div>
<div class="parent">
  <div class="circle large round"></div>
</div>
DecPK
  • 24,537
  • 6
  • 26
  • 42
Ghayas Ud Din
  • 315
  • 2
  • 14
  • 1
    `hasOverlap` by using the hypotenuse function and comparing this to a radius always checks to see if two circles with given bounds overlap. `hasOverlap` should work like this for two circles, but should check instead if any of the bounds overlap each other for polygons. See https://stackoverflow.com/a/12067046. – Peter Warrington Aug 16 '22 at 12:04
  • But in that case, if one of them is a circle and one is a square it will still give true even if the circle and square are not overlapping. it checks if the box ( no matter what the shape is ) is overlapping or not. – Ghayas Ud Din Aug 16 '22 at 12:35
  • So you want the formula of `hasOverlap` to take into account the `border-radius` ? is it always 50% or 0% ? or could be in the middle? or in pixels? – IT goldman Aug 16 '22 at 12:39
  • One of the div will always be a circle and one of the div will be an alphabet but you can consider it a square or rectangle. – Ghayas Ud Din Aug 16 '22 at 12:41

0 Answers0