【问题标题】:Stop rotating images if mouse pointer is too close如果鼠标指针太近,则停止旋转图像
【发布时间】:2013-11-26 14:52:07
【问题描述】:

我有一个根据鼠标指针移动的位置旋转的图像。我想要完成的是这个。如果指针离得太近,图像应该一起停止移动。

这里有一张图片让它更清楚一点:

这是旋转的代码:

$(window).on('mousemove', function (e) {

      //Current position
      var p1 = {
        x: player.offset().left,
        y: player.offset().top
      };     
      //Future position
      var p2 = {
        x: e.offsetX,
        y: e.offsetY
      };

      //Angle between them in degrees
      var angleDeg = Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180 / Math.PI;
      angleDeg -= 90;
        //Animate the whole thing
         player.css('-webkit-transform', 'rotate(' + angleDeg + 'deg)');
    });

这是我迄今为止尝试过的,但没有成功:

function tooClose(object1, object2){
    if (object1.x < object2.x && object1.x + object1.width  > object2.x &&
    object1.y < object2.y && object1.y + object1.height > object2.y) {
        return true;
    }
}

Full fiddle here

谢谢!

【问题讨论】:

    标签: javascript object rotation mouseover


    【解决方案1】:

    这是固定的jsFiddle

    主要问题是您的第二点是使用e.offsetXe.offsetY - 当您“靠近”图像时,这些会产生意想不到的结果,或者换句话说,您在图像上,并且您得到了@ 987654325@ 相对于 图像 而不是屏幕。您想要的是每次都获得绝对屏幕值。

    换行:

    var p2 = {
        x: e.offsetX,
        y: e.offsetY
      };
    

    到这里:

    var p2 = {
        x: e.clientX,
        y: e.clientY
      };
    

    修复了这个问题。

    我还冒昧地修复了偏移旋转枢轴。首先,图像是动态定位的——因此它的位置发生了变化,您还使用它的左上角作为中心。为了解决这些问题,我把它放在一个容器中,并使用容器的中心作为枢轴。 (见jsFiddle)。

    【讨论】:

    • 如果你删除 -webkit- 这在 Chrome 和 Firefox 中有效;)
    • @core1024 -webkit- 适用于 chrome 和 safari。 -moz- 用于火狐 :)
    【解决方案2】:

    您可以使用鼠标位置和图像中心之间的欧几里得距离:http://en.wikipedia.org/wiki/Euclidean_distance

    一旦你获得距离,当它小于给定阈值时,执行你需要的功能(我认为你的情况是“停止”)。

    【讨论】:

      【解决方案3】:

      您可以检查图像是否被悬停。

      // Declare the hover checking function...
      function idIsHovered(id){
          return $("#" + id + ":hover").length > 0;
      }
      
      // Check if the picture is being hovered
      if(!idIsHovered('player')){
          // If not: do your thing.
      }
      

      这是DEMO

      注意:“检查悬停”功能来自this answer

      【讨论】:

        【解决方案4】:

        使用此功能:

        function Distance( p1, p2 ){
            var x,y = 0;
            x = p2.x - p1.x;
            x = x * x;
            y = p2.y - p1.y;
            y = y * y;
            return Math.sqrt( x + y );
        }
        

        Fiddle

        当您就在车上时,仍然有点摇摆不定。 不要酒后驾车和编码!

        啊,@MeLight 已经解决了这个问题。指定司机!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-30
          • 2016-11-10
          • 1970-01-01
          • 2013-04-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多