效果
要达到无论在什么机器上,算出来的速度是一样的。
思路:
计算两次mousemove之间的位移和时间,就可以算出精确的速度
不要将onMousemove的调用时间间隔看成是均等的,事实上也不是均等的,而是根据机器的运行状况实时调整的,所以两次调用之间的时间间隔不能看成是单位时间。关于mousemove的讨论
示例
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;}
参考
1.Calculating mouse velocity with accuracy