Calculate the diameter of a circle to fill the rectangle according to the mouse position

Asked

Viewed 541 times

1

My question is more for math than programming. but Anyway...

I am creating a small script to determine the position (which is done by the mouse) and the diameter of a circle that is inside a rectangle. So far I’ve been able to determine the maximum diameter of the circle that equals the diagonal of the rectangle.

However, this only works properly when the cursor is in the corners of the rectangle. When the cursor is in the center or at the edges of the rectangle, the circle is larger than the rectangle. http://codepen.io/salomaosnff/pen/rLwGBV

  • Do you want the circle to always stay entirely inside the rectangle? I ask this because in your example it is not.

  • From the center to the edge

1 answer

1


I believe what you want is in the code below:

Javascript:

var quadrado  = $("#quadrado"), 
    circulo   = $("#circulo"),
    offset    = quadrado.offset();

$(document).on('mousemove', function(e){
  var x = e.pageX - offset.left;
  var y = e.pageY - offset.top;

  var w = quadrado.outerWidth();
  var h = quadrado.outerHeight();

  var hCirculo = Math.min(Math.max(h - y, y), h);
  var wCirculo = Math.min(Math.max(w - x, x), w);

  var catetoH = Math.min(Math.max(hCirculo, y), h);
  var catetoW = Math.min(Math.max(wCirculo, x), w);

  var raio = Math.sqrt((catetoH*catetoH) + (catetoW*catetoW));
  var diametro = raio * 2;

  var top = y - raio;
  var left = x - raio;

  if (x < 0)
    left = -raio;
  else if (e.pageX > offset.left + w)
    left = w - raio;

  if (y < 0)
    top = -raio;
  else if (e.pageY > offset.top + h)
    top = h - raio;

  circulo.css({
    width: diametro,
    height: diametro,
    top: top,
    left: left
  });
});

CSS:

html, body{
  background: #333;
}
#quadrado{
  width: 90px;
  height: 50px;
  background: #FFF;
  position: absolute;
  top: 40%;
  left: 45%;
}

#circulo{
  background: yellow;
  opacity: 0.75;
  border-radius: 50%;
  position: absolute;
}

HTML:

<div id="quadrado">
<div id="circulo">
  • Almost that, only the circle became too small. He must fill the whole rectangle without leaving leftovers on the opposite side of the cursor. Just like when the cursor is in the corners.

  • Even if part of the circle is outside the rectangle? In your question you specified "a circle that is inside a rectangle".

  • yes, the rectangle will overflow Hidden, but the corner of the rectangle must be on the edge of the circle, because the circle will have an Animate() and this causes a delay.

  • 1

    I’ve made some changes, but I’m still not sure what you’re looking for.. rs See if you’ve come close now.

  • You came very close! But the circle needs to be a little bigger, until you fill the rectangle to look like this: http://prntscr.com/botgzq

  • Now I think it was. Take a look.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.