Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make image not snap to cursor?

Trying to make an image follow the mouse. It works, but the problem I’m having is that upon refresh/first movement, the image will appear at the top left and snap to the mouse position. How do I get rid of that process and just have the image appear from under the mouse?

const mouse_trail = document.getElementById('mouse_trail');

window.onmousemove = e => {
  mouse_trail.style.opacity = 1;

  const x = e.clientX - mouse_trail.offsetWidth / 2,
    y = e.clientY - mouse_trail.offsetHeight / 2;

  const keyframes = {
    transform: `translate(${x}px, ${y}px)`
  }

  mouse_trail.animate(keyframes, {
    duration: 800,
    fill: 'forwards'
  });
}
#mouse_trail {
  height: 20px;
  width: 20px;
  position: fixed;
  left: 0px;
  top: 0px;
  z-index: -1;
  opacity: 0;
  transition: opacity 500ms ease;
}

#mouse_trail img {
  position: absolute;
  height: 80px;
  width: 80px;
  animation: rotate 2.5s infinite linear;
}

@keyframes rotate {
  100% {
    transform: rotate(360deg);
  }
}
<div id="mouse_trail">
  <img src="https://picsum.photos/200/300" />
</div>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Set a flag to check if this is the first time you are moving the element, and if so, animate it to that target position with a duration of 0.

const mouse_trail = document.getElementById('mouse_trail');
let didMoveYet = false;

window.onmousemove = e => {
  mouse_trail.style.opacity = 1;

  const x = e.clientX - mouse_trail.offsetWidth / 2,
    y = e.clientY - mouse_trail.offsetHeight / 2;

  const keyframes = {
    transform: `translate(${x}px, ${y}px)`
  }

  if (!didMoveYet) {
    didMoveYet = true;
    mouse_trail.animate(keyframes, {
    duration: 0,
    fill: 'forwards'
  });
  }
  
  mouse_trail.animate(keyframes, {
    duration: 800,
    fill: 'forwards'
  });
}
#mouse_trail {
  height: 20px;
  width: 20px;
  position: fixed;
  left: 0px;
  top: 0px;
  z-index: -1;
  opacity: 0;
  transition: opacity 500ms ease;
}

#mouse_trail img {
  position: absolute;
  height: 80px;
  width: 80px;
  animation: rotate 2.5s infinite linear;
}

@keyframes rotate {
  100% {
    transform: rotate(360deg);
  }
}
<div id="mouse_trail">
  <img src="https://picsum.photos/200/300" />
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading