Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect circle overlap

I'm trying to trigger a hover function when ANY part of a fake cursor hovers over a circle.

I have played around with the X and Y positions of the fake cursor, but that only works well for one direction. Is there a smarter way to go about this?

Here's a pen showing what I'm trying to do: trigger a hover function when any part of the pink circle (fake cursor) touches the green circle.

https://codepen.io/Jessels/pen/LYPxmqx

$('.cursor')
  .eq(0)
  .css({
        left: e.pageX - 20,
        top: e.pageY - 5
  });
like image 704
Jess Avatar asked Dec 12 '25 14:12

Jess


1 Answers

You can add this to your mousemove event.

Here we are finding the intersections and if the "cursor" is within the circle.

Here is where I found this code: Fiddle

Here is my CodePen Demo

$(document).mousemove(function(e) {

  $('.cursor').eq(0).css({
    left: e.pageX - 25,
    top: e.pageY - 20
  });

  // circles
  var c1 = $('.cursor');
  var c2 = $('.circle');

  // radius
  var d1 = c1.outerWidth(true) / 2;
  var d2 = c2.outerWidth(true) / 2;

  // center of first circle
  var x1 = c1.offset().left + c1.width() / 2;
  var y1 = c1.offset().top + c1.height() / 2;

  // center of second circle
  var x2 = c2.offset().left + c2.width() / 2;
  var y2 = c2.offset().top + c2.height() / 2;

  function calc() {
    var a = d2;
    var b = d1;
    var c = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    var d = (b * b + c * c - a * a) / (2 * c);
    var h = Math.sqrt((b * b) - (d * d));
    if (d < 0 || $.isNumeric(h)) {
      c2.css('background', 'blue');
    } else {
      c2.css('background', 'green');
    }
  }
  calc();


});
.cursor {
  height: 50px;
  width: 50px;
  border-radius: 50%;
  position: absolute;
  pointer-events: none;
  z-index: 999;
  background: hotpink;
}

.circle {
  border-radius: 50%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 200px;
  height: 200px;
  background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cursor"></div>

<div class="circle">
  <div class="inter1 inter"></div>
  <div class="inter2 inter"></div>
  <div>
like image 77
Souleste Avatar answered Dec 15 '25 06:12

Souleste



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!