最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get mouse moving speed - Stack Overflow

programmeradmin2浏览0评论

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.

/

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/58tjr9o1/

Share Improve this question edited Aug 5, 2017 at 7:57 ShibinRagh asked Aug 5, 2017 at 7:49 ShibinRaghShibinRagh 6,6564 gold badges37 silver badges61 bronze badges 2
  • How abt this – Durga Commented Aug 5, 2017 at 7:56
  • Mouse moving speed – ShibinRagh Commented Aug 5, 2017 at 7:56
Add a ment  | 

2 Answers 2

Reset to default 7

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.

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;


});
发布评论

评论列表(0)

  1. 暂无评论