我如何使用 atan2() 使这个 div 从它的一端而不是它的中心旋转

How do I get this div to rotate from one of its end and not its center using atan2()

我不希望下面的代码中的 div.stick 根据杆的中心旋转。现在看起来旋转原点位于中心我希望旋转原点位于底部。当鼠标移动并且鼠标与操纵杆顶部对齐时,操纵杆应旋转。它应该看起来像 this(旋转原点在底部)

Javascript:

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

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


       })

HTML:

<div class="display"></div>
<div class="wrapper">
    <div class="stick"></div>
</div>

CSS:

.wrapper{
    width: 500px;
    height: 400px;
    position: relative;
    border:1px solid green;
}
.stick{
    width: 3px;
    height: 200px;
    position: absolute;
    left: 50%;
    top: 25%;
    background: green;
}

最重要的部分是重新设置旋转中心。添加到 CSS .stick

transform-origin: 50% 100%;

以底部中间为旋转中心。现在您需要调整角度计算以相对于这个新中心。添加新变量

var sRotMidX = sLeft+sWidth/2, sRotMidY=sTop+sHeight;

并将角度计算更改为

atan = Math.atan2(e.pageY - sRotMidY , e.pageX - sRotMidX) + Math.PI/2;

或者相同数量没有多个来源,中心在 9:1 分裂:

var fmidX =.5, fmidY=.9;
stick.css({"transform-origin" : (100*fmidX)+"% "+(100*fmidY)+"%"});
var sRotMidX = sLeft+sWidth*fmidX, sRotMidY=sTop+sHeight*fmidY;