Rotating a moving image with jquery

Solution 1:

A must-know about coding:

When coding, declaring a variable like the following works differently than you think it does.

var var1 = 2;
var var2 = var1;

Instead of var2 always being the value of var1, it just sets var2 to whatever var1 is at the moment.

Which means setting var1 to 3 will still keep var2 at 2.

Confused? Check this post to see what I mean! (To be honest, this confused me more)

How does this relate?

In the following line, you do the following:

let boxBoundingRect = box.getBoundingClientRect();
let boxCenter = {
  x: boxBoundingRect.left + boxBoundingRect.width / 2,
  y: boxBoundingRect.top + boxBoundingRect.height / 2
};

But when the position changes, those values don't change. Rather, they stay the same.

What do you do?

In this function:

document.addEventListener("mousemove", e => {
  let angle = Math.atan2(e.pageX - boxCenter.x, -(e.pageY - boxCenter.y)) * (180 / Math.PI);
  box.style.transform = `rotate(${angle}deg)`;
})

Recalculate the bounding box so it looks like the following:

document.addEventListener("mousemove", e => {
  boxBoundingRect = box.getBoundingClientRect();
  boxCenter = {
    x: boxBoundingRect.left + boxBoundingRect.width / 2,
    y: boxBoundingRect.top + boxBoundingRect.height / 2
  };
  let angle = Math.atan2(e.pageX - boxCenter.x, -(e.pageY - boxCenter.y)) * (180 / Math.PI);
  box.style.transform = `rotate(${angle}deg)`;
})

Snippet

$(document).mousemove(function(e) {
  /*duration determines the speed of the animation (in this case, the speed to which prgm follows)*/
  $("#image").stop().animate({
    left: e.pageX,
    top: e.pageY
  }, {
    duration: 5000
  });
});


let box = document.querySelector(".box");
let boxBoundingRect = box.getBoundingClientRect();
let boxCenter = {
  x: boxBoundingRect.left + boxBoundingRect.width / 2,
  y: boxBoundingRect.top + boxBoundingRect.height / 2
};

document.addEventListener("mousemove", e => {
  boxBoundingRect = box.getBoundingClientRect();
  boxCenter = {
    x: boxBoundingRect.left + boxBoundingRect.width / 2,
    y: boxBoundingRect.top + boxBoundingRect.height / 2
  };
  let angle = Math.atan2(e.pageX - boxCenter.x, -(e.pageY - boxCenter.y)) * (180 / Math.PI);
  box.style.transform = `rotate(${angle}deg)`;
})
.box {
  background-color: black;
  width: 30px;
  height: 30px;
  position: absolute;
  left: 200px;
  top: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <div class="box" id="image"> </div>
</body>