Javascript:跟随光标但保持在一个圆圈内而不是矩形div

时间:2013-10-05 16:10:25

标签: javascript jquery html css

我正在尝试获取下面的jsfiddle示例以使黄色圆圈div 跟随鼠标 但是约束到圆圈而不是方形(div)

http://jsfiddle.net/fhmkf/

JS代码如下:

var mouseX = 0, mouseY = 0, limitX = 150-15, limitY = 150-15;
$(window).mousemove(function(e){
   mouseX = Math.min(e.pageX, limitX);
   mouseY = Math.min(e.pageY, limitY);
});

// 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});

}, 30);

我理解代码的结构和方法,只是不太熟悉语法!

更新limitX/Y并投放额外radiusdistance个变量的最佳位置在哪里?

1 个答案:

答案 0 :(得分:2)

您可以通过计算远离圆心的距离来实现此目的(使用Math.sqrt (x * x + y * y)计算2D距离)。然后检查距离是否大于您想要约束的圆的半径。如果是,请缩小距离以匹配约束半径。

以下是片段:

var mouseX = 0, mouseY = 0, limitX = 150-15, limitY = 150-15;
var centerX = limitX / 2, centerY = limitY / 2;
var radius = centerX;
$(window).mousemove(function(e) {
   var diffX = e.pageX - centerX;
   var diffY = e.pageY - centerY;

   // Get the mouse distance from the center
   var r = Math.sqrt(diffX * diffX + diffY * diffY);

   if (r > radius) {
     // Scale the distance down to length 1 
     diffX /= r;
     diffY /= r;

     // Scale back up to the radius
     diffX *= radius;
     diffY *= radius;
   }

   mouseX = centerX + diffX;
   mouseY = centerY + diffY;
});

这是完整的代码:http://jsfiddle.net/fhmkf/