如何在JavaScript中旋转跟随光标的图像?

时间:2016-09-19 11:30:14

标签: javascript jquery html

我有跟随鼠标光标的图像。

HTML:

<img id="cow" src="https://icons.iconarchive.com/icons/gakuseisean/ivista-2/128/Alarm-Arrow-Right-icon.png" height="30px" width="30px" style="position: absolute; top: 50%; left: 50%;"/> 

Javascript:

var mouseXY = {};
$( document ).on( "mousemove", function( event ) {
  mouseXY.X = event.pageX; 
  mouseXY.Y = event.pageY;
});
var iCow = $("#cow");
var cowInterval = setInterval(function()
{
  var cowXY = iCow.position();
  var diffX = cowXY.left - mouseXY.X;
  var diffY = cowXY.top - mouseXY.Y;
  var newX = cowXY.left - diffX / 1000;
  var newY = cowXY.top - diffY / 1000;
  iCow.css({left: newX, top: newY});
}, 10);

JSFiddle example

如何沿光标方向旋转图像?
我试图用transform: rotate()

来做
var cowInterval = setInterval(function()
{
  var cowXY = iCow.position();
  var diffX = cowXY.left - mouseXY.X;
  var diffY = cowXY.top - mouseXY.Y;
  var newX = cowXY.left - diffX / 1000;
  var newY = cowXY.top - diffY / 1000;
  var tan = diffX / diffY;
  var atan = Math.atan(tan);
  iCow.css({left: newX, top: newY, transform: "rotate(" +((-1)*atan - Math.PI/2)+ "rad)"});
}, 10);

但未成功

1 个答案:

答案 0 :(得分:2)

更改光标位置时,只需更改transform(rotate)css属性,请记住光标实际上改变了位置。

添加这两个if-else条件以使图像以正确的方向旋转

 if(diffY > 0 && diffX > 0) {

    atan += 180; 
  }
 else if(diffY < 0 && diffX > 0) {

    atan -= 180;
  }

我想这就是你想要的。

var mouseXY = {};
    $( document ).on( "mousemove", function( event ) {
      mouseXY.X = event.pageX; 
      mouseXY.Y = event.pageY;
    });
    var iCow = $("#cow");
    var prevXY = {X: null, Y: null};
    var cowInterval = setInterval(function()
    {
    
      
      if(prevXY.Y != mouseXY.Y || prevXY.X != mouseXY.X && (prevXY.Y != null || prevXY.X != null)) {
      
      var cowXY = iCow.position();
      var diffX = cowXY.left - mouseXY.X;
      var diffY = cowXY.top - mouseXY.Y;
      var tan = diffY / diffX;
     
      var atan = Math.atan(tan)* 180 / Math.PI;;
       if(diffY > 0 && diffX > 0) {
      
      	atan += 180; 
      }
      else if(diffY < 0 && diffX > 0) {
      
      	atan -= 180;
      }
      
      prevXY.X = mouseXY.X;
      prevXY.Y = mouseXY.Y;
      iCow.css({transform: "rotate(" + atan + "deg)"});
    }
    }, 10);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="cow" src="https://icons.iconarchive.com/icons/gakuseisean/ivista-2/128/Alarm-Arrow-Right-icon.png" height="30px" width="30px" style="position: absolute; top: 50%; left: 50%;"/>