鼠标速度javascript函数

时间:2013-11-05 16:47:49

标签: javascript performance cursor

使用一些javascript。我找到了一个非常好的函数来计算光标的速度。问题是我想返回实际值,而不是回调。你会怎么做?

        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;
            // update values:
            x = new_x;
            y = new_y;
            t = new_t;
            var velocity = Math.sqrt(x_dist*x_dist+y_dist*y_dist)/interval;
            callback(velocity);
        };
    }

2 个答案:

答案 0 :(得分:2)

然后,然后将该函数更改为返回速度,而不是“回调(速度)”

Js Fiddle sample

或者你可以按照预期的方式使用它

makeVelocityCalculator(initialEvent, function(velocity) {
   console.log("velocity is", velocity);
});
is pretty much same as 
var velocity = makeVelocityCalculator(initialEvent);
console.log("velocity is", velocity);

答案 1 :(得分:1)

 function calculateVelocity(e_init) {
    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;
        // update values:
        x = new_x;
        y = new_y;
        t = new_t;
        var velocity = Math.sqrt(x_dist*x_dist+y_dist*y_dist)/interval;
        return velocity;
    };
}

var velocity = calculateVelocity(e_init)(e);
// OR
var v_f = calculateVelocity(e_init);
// then some code ...
v_f(e);

如果希望调用(function(){})()来返回速度,请使用立即调用函数calculateVelocity,否则返回函数,然后返回速度。