使用atan2()将一个div旋转到鼠标方向

3
我希望鼠标能够与div的顶部对齐,当鼠标移动时,div应该旋转并且顶部与鼠标对齐。我想使用atan2函数。它应该看起来像这样 this
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:

.wrapper{
    width: 500px;
    height: 400px;
    position: relative;
    border:1px solid green;
}
.stick{
    width: 3px;
    height: 200px;
    position: absolute;
    left: 50%;
    top: 50%;
    background: green;
    transform: rotate(90deg);
}

HTML:

<div class="wrapper">
    <div class="stick"></div>
</div>
2个回答

3

我做了一个在这里运行的东西。

看起来你的居中不太对 - 你需要考虑到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度。然后我在想,为什么容器需要play(-200, -250)来居中。因为容器只是用来设置边框样式的。我只是认为我需要两个边来获取atan2()的角度,然后旋转。 - jack blank
1
点(250,200)是棍子的中心 - 因此您正在旋转从该点到鼠标的角度。您旋转90度,因为棍子最初是垂直的,但角度0是水平向右的。 - sje397
抱歉让这个问题一直持续,但我很困扰,因为我无法将div的一端固定。通过您的回答,看起来旋转原点在中心,而我正在尝试将其移到底部(边缘),就像这里:https://www.khanacademy.org/computer-programming/atan2y-x-processingjs/6206505994420224。先谢谢了。 - jack blank
嗨,我又提出了一个与我上次评论中提出的问题有关的问题。请帮忙。http://stackoverflow.com/questions/33459736/how-do-i-get-this-div-to-rotate-from-one-of-its-end-and-not-its-center-using-ata - jack blank

0
问题在于角度计算phi=atan2(y,x)假设一个“正常”的笛卡尔坐标系,其中y轴向上。但在屏幕坐标中,它指向下。因此,您应该使用phi=atan2(-y,x)
但为了确保,您应该尝试并报告当使用旋转角度为0deg90deg时,栏指向何处。使用您的代码,旋转中心是栏的中心,因此很难确定方向,但似乎0deg指向上方,并且角度顺时针应用。因此,对于内部坐标系统,其中0°是X轴,90°是Y轴,X = centery-yY=x-centerx,因此

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接