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">
Do you want the circle to always stay entirely inside the rectangle? I ask this because in your example it is not.
– Waldir J. Pereira Junior
From the center to the edge
– Salomão Neto