Incorrect rotation behavior when adding smooth animation to an element

30 Views Asked by At

There is an arrow element that should follow the cursor, like this: https://codepen.io/andreyka-g/pen/oZyREx In the link is an example of what it should look like, an example of the code I use is provided below. When I try to add a smooth animation to it, the arrow starts to behave incorrectly.

Regarding the incorrect behavior: when the rotation value reaches 180deg or -180deg, it scrolls the other way. I also tried to use Gsap

How can this be fixed and what other ways are there to implement such animation?

Code Snippet

document.addEventListener('mousemove', function(event) {
var mouseX = event.clientX;
var mouseY = event.clientY;

var arrows = document.querySelectorAll('.cta-link-icon');

arrows.forEach(function(arrow) {
    var arrowRect = arrow.getBoundingClientRect();
    var arrowCenterX = arrowRect.left + arrow.offsetWidth / 2;
    var arrowCenterY = arrowRect.top + arrow.offsetHeight / 2;
    var angle = Math.atan2(mouseY - arrowCenterY, mouseX - arrowCenterX);
    angle = angle * (180 / Math.PI);

    arrow.style.transform = 'rotate(' + angle + 'deg)';
});
});
html, body {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.cta-link-icon {
  width: 50px;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  pointer-events: none;
  transition: transform 0.01s;
}
   <div class="cta-link-icon">
<svg width="42" height="36" viewBox="0 0 42 36" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M25.5435 1.33321L41.2935 17.0832C41.4179 17.2017 41.517 17.3442 41.5847 17.5022C41.6524 17.6601 41.6873 17.8301 41.6873 18.002C41.6873 18.1738 41.6524 18.3438 41.5847 18.5017C41.517 18.6597 41.4179 18.8022 41.2935 18.9207L25.5435 34.6707C25.2998 34.9144 24.9694 35.0513 24.6248 35.0513C24.2802 35.0513 23.9497 34.9144 23.706 34.6707C23.4623 34.427 23.3254 34.0966 23.3254 33.752C23.3254 33.4074 23.4623 33.0769 23.706 32.8332L37.2029 19.3145L1.87476 19.3145C1.52666 19.3145 1.19282 19.1762 0.946678 18.93C0.700537 18.6839 0.562256 18.3501 0.562256 18.002C0.562256 17.6539 0.700537 17.32 0.946678 17.0739C1.19282 16.8277 1.52666 16.6895 1.87476 16.6895L37.2029 16.6895L23.706 3.17071C23.4623 2.92704 23.3254 2.59656 23.3254 2.25196C23.3254 1.90736 23.4623 1.57688 23.706 1.33321C23.9497 1.08954 24.2802 0.952651 24.6248 0.952651C24.9694 0.952651 25.2998 1.08954 25.5435 1.33321Z" fill="currentColor"></path>
</svg></div>

I changed the code to the one I use now. This problem disappears if you set the animation time to 0.01, but in this case the animation will be very fast, i.e. it is no longer visible

0

There are 0 best solutions below