Calculate mouse speed with accuracy

I made a little script to infer the speed at which the mouse moves. The problems that arise for me is that sometimes the script outputs an inaccurate number among the numbers and discards it all. In addition, the script does not always end when the user releases the mouse button. To solve the first problem, I suggest that I could possibly put the values ​​in an array and then define outlier, but I hope someone here can just tell me that I'm doing something stupid, and there is a way fix my code to make it more efficient.

JS:

var test_obj = { mouse_coors: function(x2) { $(document).on("mousemove", function(e) { var x = e.clientX, velocity = Math.abs(x-x2); console.log(velocity); $(document).off("mousemove"); setTimeout(function() { x2 = e.clientX; test_obj.mouse_coors(x2); }, 100); }); $(document).on("mouseup", function() { $(document).off("mouseup").off("mousemove"); }); }, }; $(document).ready(function() { $('#testbox').on("mousedown", function() { test_obj.mouse_coors(0); }); }); 

HTML:

JSfiddle: http://jsfiddle.net/mkb2t/

+4
source share
1 answer

Just because it's not mouse speed. What you think now is how far the mouse moved in the x direction. This is called distance.

The inaccuracy you are experiencing may be due to ignoring the y-direction and the inaccuracy of setTimeout - using Date timestamps.

In addition, you create a cascade of mousemove handlers (which is not only wrong, but also poorly efficient). At each event (and they are quite common!) You wait 0.1 s, and then add a new listener that will be displayed at each event, and then how far the mouse moved from the first event. Another problem is that you call the mouse_coors function with a value of 0 when you click the mouse, but the mouse is unlikely to be there.

Better: save current mouse coordinates globally. Each time you update them, calculate the difference and divide it by the time elapsed since the last update. Then record the speed.

 function makeVelocityCalculator(e_init, callback) { var x = e_init.clientX, y = e_init.clientY, t = Date.now(); return function(e) { var new_x = e.clientX, new_y = e.clientY, new_t = Date.now(); var x_dist = new_x - x, y_dist = new_y - y, interval = new_t - t; var velocity = Math.sqrt(x_dist*x_dist+y_dist*y_dist)/interval; callback(velocity); // update values: x = new_x; y = new_y; t = new_t; }; } $(document).ready(function() { $('#testbox').on("mousedown", function(e) { var log = makeVelocityCalculator(e, function(v) { console.log(v+"pixel/ms"); }); $(document).on("mousemove", log).one("mouseup", function(){ $(document).off("mousemove", log); }); }); }); 

updated violin

+12
source

Source: https://habr.com/ru/post/1490171/


All Articles