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

1

My question is more about math than programming. But anyway ...

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

However, this only works correctly when the cursor is at the corners of the rectangle. When the cursor is in the center or the edges of the rectangle, the circle becomes larger than the rectangle. link

    
asked by anonymous 04.07.2016 / 21:50

1 answer

1

I believe that whatever 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">
    
04.07.2016 / 22:20