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 :
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>