将元素限制为mousemove上的圆形容器轮廓

时间:2014-12-29 09:30:28

标签: javascript jquery mouse coordinates

我有一个小div,我设置跟随我的鼠标,但仍然限于父div维度。这是FIDDLE

这是我用来使跟随者div跟随鼠标并限制为父级大小的脚本。完整的代码可以在小提琴中看到。

var mouseX = 0, mouseY = 0, limitX = $('.container').width()-15, limitY = $('.container').height()-15;
$(window).mousemove(function(e){
var offset = $('.container').offset();
var halfContWidth = $('.container').width()/2;
var halfContHeight = $('.container').height()/2;
mouseX = Math.min(e.pageX - offset.left, limitX);
mouseY = Math.min(e.pageY - offset.top, limitY);
if (mouseX < 0) mouseX = 0;
if (mouseY < 0) mouseY = 0;
$('.log').html("DivX: " + Math.round(mouseX - halfContWidth) + " DivY: " + Math.round(mouseY - halfContHeight));
});

$(window).resize(function(){
    limitX = $('.container').width()-15;
    limitY = $('.container').height()-15;
});


// cache the selector
var follower = $("#follower");
var xp = 0, yp = 0;
var loop = setInterval(function(){
// change 12 to alter damping higher is slower
xp += (mouseX - xp) / 12;
yp += (mouseY - yp) / 12;
follower.css({left:xp, top:yp});

},5);

但是,如果我想要限制器div与边界半径并且仍然将鼠标跟随器限制为其圆形轮廓怎么办? FIDDLE

1 个答案:

答案 0 :(得分:2)

如果您希望鼠标移动仅在container div中,请将$(window).mousemove更改为:

$('.container').mousemove...

这是两个条件的小提琴:Rectangle Circle

修改

我使用毕达哥拉斯方程并实现了这部分代码:

if (Math.sqrt(Math.pow(Math.abs(e.pageX - offset.left - halfContWidth), 2) + Math.pow(Math.abs(e.pageY - offset.top - halfContHeight), 2)) > newDim / 2) {

        var ratio = (mouseX - halfContWidth)/(mouseY - halfContHeight);
        var sign = 1;

        if(mouseX - halfContWidth < 0)
            sign = -1;

        mouseX = Math.sqrt(Math.pow(ratio,2)*Math.pow(newDim,2)/4/(1+Math.pow(ratio,2))) * sign;            
        mouseY = (mouseX/ratio);

        mouseX += halfContWidth;
        mouseY += halfContHeight;

    }

检查鼠标位置是否在圆圈外,然后相应地改变光标在圆圈中的位置。我使用了这样的等式:(newDim/2)^2 = (mouseX)^2 + (mouseY)^2

这是小提琴:DEMO

编辑更新小提琴,将鼠标光标指向红色光标的中间,将5添加到xp += (mouseX - xp - 5) =&gt; FIDDLE