2017-08-05 133 views
0

我沒有得到一個計算器精確解/度計算,所以我創建了一個問題獲取鼠標移動速度

var timestamp = null; 
var mY = 0; 
$(document).mousemove(function(e) { 
    var now = Date.now(); 
    currentmY = e.pageY; 



    mY = e.pageY; 
    timestamp = now; 
}); 

我需要一個速度值,當鼠標移動垂直角度。

https://jsfiddle.net/58tjr9o1/

+0

如何abt [this](https://stackoverflow.com/a/6417110/3551786) – Durga

+0

鼠標移動速度 – ShibinRagh

回答

1

的速度只需要簡單地花時間劃分的距離:

speed = distance/time 

距離只是currentmY - mY,而時間是now - timestamp。所以,最後,你會得到:

var timestamp = 0; 
var mY = 0; 
$(document).mousemove(function(e) { 
    var now = Date.now(); 
    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; 
}); 

不是* 1000,因爲時間戳是毫秒。速度在這裏_pixels /秒`。

請參閱this updated fiddle

1

下面的代碼將始終與ID =「更新速度」跨度更新鼠標的垂直運動速度。代碼是不言自明的,它只是保存當前位置,前一個位置,當前時間和前一個時間,然後使用此公式計算速度(速度=(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; 


});