【问题标题】:Rotate a div towards the direction of the mouse using atan2()使用 atan2() 向鼠标方向旋转 div
【发布时间】:2015-10-31 07:18:12
【问题描述】:

我希望鼠标移动到 align 与 div 的 top 和 div 应该 rotate 当鼠标移动时 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>

【问题讨论】:

    标签: javascript jquery html css math


    【解决方案1】:

    我做了一些有用的东西here

    您似乎没有正确居中 - 您需要考虑 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 用于居中)。因为容器只是为边框样式而存在。我只是认为我需要 2 个边来获得 atan2() 的角度然后旋转。
    • 点 (250, 200) 是棒的中心 - 所以你从那个点旋转到鼠标的角度。您旋转了 90 度,因为杆最初是垂直的,但角度 0 是向右水平的。
    • 很抱歉让这个问题保持开放,但让我感到困扰的是,我可以让它与 div 的一端固定在一起工作。根据您的回答,旋转原点似乎位于中心,我正试图将其移至底部(边缘)。像这儿。 khanacademy.org/computer-programming/atan2y-x-processingjs/… 。提前致谢。
    • 嗨,我提出了另一个与我在上一条评论中提出的问题有关的问题。请帮忙。 stackoverflow.com/questions/33459736/…
    【解决方案2】:

    问题在于角度计算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)
    

    【讨论】:

      猜你喜欢
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      • 1970-01-01
      • 2012-06-18
      相关资源
      最近更新 更多