计算鼠标移动角度(以度为单位)

Calculating angle in degrees of mouse movement

本文关键字:为单位 计算 移动 鼠标      更新时间:2023-09-26

我想计算鼠标移动的角度(以度为单位)。虽然我知道你不必在直线上移动鼠标,但我只是试图根据起点和终点来计算它,以创建一个漂亮的直角。

log("ANGLE: " + getAngle(x1, y1, x2, y2));给出了奇怪的结果:

ANGLE: 0.24035975832980774 
mouse has stopped
ANGLE: 1.334887709726425 
mouse has stopped
ANGLE: 0.2722859857950508
mouse has stopped
ANGLE: 0.3715485780567732
mouse has stopped

代码:

        $("canvas").mousemove(function(e) {                 
            getDirection(e);
            if (!set) {
                x1 = e.pageX, //set starting mouse x
                y1 = e.pageY, //set starting mouse y
                set = true;
            }   
            clearTimeout(thread);
            thread = setTimeout(callback.bind(this, e), 100);
        });
        function getAngle (x1, y1, x2, y2) {
            var distY = Math.abs(y2-y1); //opposite
            var distX = Math.abs(x2-x1); //adjacent
            var dist = Math.sqrt((distY*distY)+(distX*distX)); //hypotenuse, 
               //don't know if there is a built in JS function to do the square of a number
            var val = distY/dist;
            var aSine = Math.asin(val);
            return aSine; //return angle in degrees
        }
        function callback(e) {
            x2 = e.pageX; //new X
            y2 = e.pageY; //new Y
            log("ANGLE: " + getAngle(x1, y1, x2, y2));
            log("mouse has stopped");   
            set = false;
        }

您的计算似乎是正确的,但问题是Math.asin(val)返回的值是弧度。使用以下功能转换为度数:

Math.degrees = function(radians) {
    return radians*(180/Math.PI);
}

然后调用Math.degrees(Math.asin(val)),它应该可以工作了!

使用atan2函数获取完整圆中的角度,

radians = Math.atan2(y2-y1,x2-x1);

此外,您可能希望在计算时记录x1、x2、y1、y2的值,最好只有一个跟踪鼠标位置的位置。目前,您每10ms更新一次位置(x2,y2,t2),但每次移动鼠标时都会更新(x1,y1,t1)。这可能导致非常不可预测的样本组合。

Math.asin()函数返回以弧度为单位的角度。如果你乘以180/pi,你会得到以度为单位的答案。

此外,由于您想要超过90度,因此应该放弃Math.abs调用,以便aSin的值为负值。