I would like to accurately measure the velocity of mouse movement when using requestAnimationFrame. Is this even possible? Im not sure if it is possible because the frame rate for requestAnimationFrame is not constant?
HTML:
<canvas id="demo" width="400" height="400"></canvas>
<p id="output">Velocity: </p>
CSS:
* {
margin: 0px;
cursor: none;
}
#demo {
border: 1px solid #000;
}
JS:
var canvas = document.getElementById("demo");
var output = document.getElementById("output");
var context = canvas.getContext("2d");
var x = 0;
var y = 0;
var velocity = 0;
var radius = 20;
function draw() {
context.fillStyle = 'red';
context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI);
context.fill();
}
document.addEventListener('mousemove', function(e) {
x = e.clientX;
y = e.clientY;
});
function loop() {
context.clearRect(0, 0, 400, 400);
draw();
output.innerHTML = "Velocity: " + velocity;
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
Date.now()
to get a current timestamp in ms – Phil