Ilya
Ilya

Reputation: 29693

How to Rotate image that follows cursor in JavaScript?

I have image that is following mouse's cursor.

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

How can I rotate image in the direction of cursor?
I have tried to do it with 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);

but unsuccessfully

Upvotes: 5

Views: 9580

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281676

You need to change only the transform(rotate) css property when changing the cursor postion, keeping in mind that the cursor actually changed position.

Add these two if-else condition to make the image rotate in the correct direction

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

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

    atan -= 180;
  }

I suppose this is what you want.

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%;"/>

Upvotes: 10

Related Questions