Javascript 使用atan2()朝鼠标方向旋转div

Javascript 使用atan2()朝鼠标方向旋转div,javascript,jquery,html,css,math,Javascript,Jquery,Html,Css,Math,我希望鼠标与div的顶部对齐,当鼠标移动时,div应旋转。我想使用atan2。它应该看起来像 Javascript: $(function() { var stick = $(".stick"), sHeight = stick.outerHeight(), sWidth = stick.outerWidth(), atan, sTop = stick.offset().top, sLeft = stick.offset(

我希望鼠标
与div的
顶部对齐
,当鼠标移动时,div应
旋转
。我想使用
atan2
。它应该看起来像

Javascript:

$(function() {
    var stick = $(".stick"), sHeight = stick.outerHeight(), 
                sWidth = stick.outerWidth(), atan,
                sTop = stick.offset().top, sLeft = stick.offset().left;

    $(document).on("mousemove", function(e) {
        // console.log(e.pageX, " ", e.pageY)
        atan = Math.atan2(e.pageY - sTop , e.pageX - sLeft ) 
        console.log(atan)
        stick.css({"transform" : "rotate("  + atan +  "rad)"} )
    })
})
css:

HTML:



问题在于角度计算
phi=atan2(y,x)
假设一个“正常”笛卡尔坐标系,其中
y
轴指向上方。在屏幕坐标中,它指向下方。因此,您应该使用phi=atan2(-y,x)

但要确保使用旋转
0deg
90deg
时,您应该尝试并报告条形图指向的位置。对于您的代码,旋转中心位于条的中间,因此很难确定方向,但似乎
0deg
指向上方,角度是顺时针应用的。因此,对于内部坐标系,其中0°为X轴,90°为Y轴,
X=centery-Y
Y=X-centerx
,因此

angle = atan2(x-centerx, centery-y)

我做了一些有用的东西

看起来您没有正确居中-您需要考虑div的宽度和容器的中心点

div.$(function(){

    var stick = $(".stick"), sHeight = stick.outerHeight(), 
                sWidth = stick.outerWidth(), atan,
                sTop = stick.offset().top, sLeft = stick.offset().left;
    $(document).on("mousemove", function(e){
        atan = Math.atan2(e.pageY - 200 , e.pageX - 250) + Math.PI/2;
        console.log(atan);

        stick.css({"transform" : "rotate("  + atan + "rad)"} );


    });
});

(我还删除了css中的旋转,并将斗杆定位在中心。)

我看到这是可行的,感谢您的回复。我不明白的第一件事是为什么你需要“Math.PI/2”。我知道那等于90度。然后,我在想为什么容器需要处于活动状态(-200,-250用于居中)。因为容器实际上就是用于边框样式的。我只是想我需要两条边来获得atan2()的角度,然后旋转。点(250200)是棒的中心-所以你从该点旋转到鼠标的角度。你旋转90,因为木棍最初是垂直的,但角度0是水平的。很抱歉,这个问题一直没有解决,但我很困扰,我可以让它工作与一个两端的div固定下来。根据你的答案,旋转原点似乎在中心,我试图将它移到底部(边缘)。就像这里。提前谢谢。嗨,我问了另一个问题,关于我在最后一次评论中提出的问题。请帮忙。
angle = atan2(x-centerx, centery-y)
div.$(function(){

    var stick = $(".stick"), sHeight = stick.outerHeight(), 
                sWidth = stick.outerWidth(), atan,
                sTop = stick.offset().top, sLeft = stick.offset().left;
    $(document).on("mousemove", function(e){
        atan = Math.atan2(e.pageY - 200 , e.pageX - 250) + Math.PI/2;
        console.log(atan);

        stick.css({"transform" : "rotate("  + atan + "rad)"} );


    });
});