Reputation: 6646
I didn't get a exact solution/calculation from stackoverflow so i created a question
var timestamp = null;
var mY = 0;
$(document).mousemove(function(e) {
var now = Date.now();
currentmY = e.pageY;
mY = e.pageY;
timestamp = now;
});
I need to get a speed value when mouse move vertical angle.
https://jsfiddle.net/58tjr9o1/
Upvotes: 3
Views: 5093
Reputation: 9881
The speed is simply the distance divided by the time it took:
speed = distance / time
The distance is currentmY - mY
, while the time is now - timestamp
. So in the end, you get:
var timestamp = 0;
var mY = 0;
$(document).mousemove(function(e) {
var now = Date.now();
var currentmY = e.screenY;
var dt = now - timestamp;
var distance = Math.abs(currentmY - mY);
var speed = Math.round(distance / dt * 1000);
console.log(dt, distance, speed);
document.getElementById("speed").innerHTML = speed;
mY = currentmY;
timestamp = now;
});
Note the * 1000
, since the timestamp is in milliseconds. The speed is here in pixels/second.
See this updated fiddle.
Upvotes: 7
Reputation: 1260
Following code will continuously update mouse's vertical movement speed in the span with id = "update-speed". Code is self explanatory and easy to understand, it just saved current position, previous position, current time and previous time and then calculates the speed using this formula (speed = (pos2 - pos1) / (time2 - time1).
HTML
<span id="update-speed">Update speed</span>
JS
var prev_time = new Date();
var prev_pos_y = 0;
$(document).mousemove(function(e) {
var now = new Date();
current_pos_y = e.pageY;
time_interval = now.getTime() - prev_time.getTime();
if(time_interval != 0)
{
speed = ( Math.abs(current_pos_y - prev_pos_y) / time_interval );
}
else
speed = 0;
console.log(speed);
$('#update-speed').text(speed);
prev_time = now;
prev_pos_y = current_pos_y;
});
Upvotes: 1