要达到无论在什么机器上,算出来的速度是一样的。计算两次mousemove之间的位移和时间,就可以算出精确的速度,不要将onMousemove的调用时间间隔看成是均等的,事实上也不是均等的
var preX = 0;
var preTime = undefined;
document.addEventListener("mousedown",onMouseDown);
function onMouseDown(event){
preTime = undefined;
document.addEventListener("mousemove",getVolecity);
document.addEventListener("mouseup",onMouseUp);
}
function onMouseUp(event){
document.removeEventListener("mousemove",getVolecity);
}
/**
* 计算速度
* @param event
*/
function getVolecity(event){
var currTime = Date.now();
if(typeof preTime != "undefined"){ //跳过第一次
var dist = event.clientX - preX;
var time = currTime - preTime;
var volecity = dist/time;
console.log("volecity:"+volecity);
}
preX = event.clientX;
preTime = currTime;
}