计算鼠标移动的角度

时间:2014-04-10 02:59:34

标签: javascript html math geometry

我想以度为单位计算鼠标移动的角度。虽然我知道你不必将笔直线移动,但我只是想根据起点和终点来计算它,以创造一个很好的直角。

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;
        }

3 个答案:

答案 0 :(得分:6)

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

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

然后拨打Math.degrees(Math.asin(val)),它应该有效!

答案 1 :(得分:5)

使用atan2函数获得整圆的角度

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

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

答案 2 :(得分:1)

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

此外,由于您需要超过90度,因此您应该放弃Math.abs来电,以便为aSin设置负值。