My little mouse speed detector, although not perfect, provides me with the current mouse speed every 100ms in the variable window.mouseSpeed.t
. I decided to implement this feature because I wanted to create a whimsical animation at the bottom edge of the screen. This animation involves a bar that grows with higher speeds and shrinks with lower speeds, all to be animated using Element.animate()
. However, I have encountered a problem: How can I change the end keyframe of the Animation
while the animation is running? My goal is to smoothly transition the bar's length.
// Below is the code that I wish to animate.
// Tracking mouse speed (I hope this code isn't too terrible):
document.addEventListener('DOMContentLoaded', trackMouseSpeed, {once:true});
function trackMouseSpeed() {
var speedX = NaN;
var speedY = NaN;
var posX = NaN;
var posY = NaN;
var speed = NaN;
document.addEventListener("mousemove", function(ev){
speedX += Math.abs(ev.movementX);
speedY += Math.abs(ev.movementY);
speed = 10*Math.sqrt(ev.movementX**2+ev.movementY**2);
window.mousePosition = {x:posX = ev.clientX,y:posY = ev.clientY};
}, false);
setInterval(function(){
[window.mouseSpeed, window.mousePosition] = [{x:speedX,y:speedY,t:speed}, {x:posX,y:posY}];
speed = totalX = totalY = 0;
}, 100);
window.trackMouseSpeed = () => {return {speed:window.mouseSpeed, pos:window.mousePosition};};
return {speed:window.mouseSpeed, pos:window.mousePosition};
}
// --- This is the code I want to have animated: ---
setInterval(() => {
document.querySelector('div#mouseSpeedIndicator').style.width = window.mouseSpeed.t+'px';
}, 100);
div#mouseSpeedIndicator {
position: fixed;
bottom: 0px;
left: 0px;
height: 33px;
background-color: green;
max-width: 100vh;
border: 0px solid green;
border-top-right-radius: 10px;
}
<!-- What I currently have -->
<div id="mouseSpeedIndicator"></div>