Estoy haciendo un juego en el que un gif sigue al cursor. ¿Hay alguna forma de reducir la velocidad para que la imagen que sigue al cursor se mueva a una velocidad constante (pero más lenta) que el propio cursor?
Básicamente, en este momento, el gif que asigné está actuando como enlace como un cursor de reemplazo. Quiero que el gif siga y alcance el cursor a su propia velocidad.
Gracias
<script> document.querySelector(".testsite").onmousemove = (e) => { const x = e.pageX - e.target.offsetLeft; const y = e.pageY - e.target.offsetTop; e.target.style.setProperty("--x", `${x}px`); e.target.style.setProperty("--y", `${y}px`); }; </script> <style> body { justify-content: center; align-items: center; min-height: 100vh; } .testsite { /* container */ width: 500px; height: 500px; position: relative; appearance: none; background: grey; padding: 10px 20px; border: none; color: white; font-size: 1.2em; cursor: none; outline: none; overflow: hidden; border-radius: 10px; box-shadow: black; } .testsite span { position: relative; pointer-events: none; } .testsite::before { --size: 0; content: ""; position: absolute; left: var(--x); top: var(--y); width: 32px; height: 32px; background-image: url("html5.gif"); animation-duration: 1s; transform: translate(-50%, -50%); } </style> <html> <body> <div class="testsite"> </div> </body> </html>Puede convertir las operaciones de coordenadas x e y de su js en una función y luego agregar un setTimeout a esa función para ejecutarla cada 100 ms o el tiempo que desee que sea el retraso. Compruébelo aquí, tenga en cuenta que también eliminé el pointer:none; de .testsite de prueba:
document.querySelector(".testsite").onmousemove = (e) => { const x = e.pageX - e.target.offsetLeft; const y = e.pageY - e.target.offsetTop; function runInt() { e.target.style.setProperty("--x", `${x}px`); e.target.style.setProperty("--y", `${y}px`); } setTimeout(runInt, 100); }; body { justify-content: center; align-items: center; min-height: 100vh; } .testsite { /* container */ width: 500px; height: 500px; position: relative; appearance: none; background: grey; padding: 10px 20px; border: none; color: white; font-size: 1.2em; outline: none; overflow: hidden; border-radius: 10px; box-shadow: black; } .testsite span { position: relative; pointer-events: none; } .testsite::before { --size: 0; content: ""; position: absolute; left: var(--x); top: var(--y); width: 32px; height: 32px; background-image: url("https://www.springbrookanimalcarecenter.com/blog/wp-content/uploads/2017/10/Springbrook_iStock-612247460-150x150.jpg"); animation-duration: 1s; transform: translate(-50%, -50%); } <html> <body> <div class="testsite"> </div> </body> </html>