简体   繁体   English

如何使用atan2()使此div从其一端旋转而不是从其中心旋转

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

I don't want the div.stick in the code below to be rotating according to the center of the stick. 我不希望下面代码中的div.stick根据棍子的中心旋转。 Right now it looks like the rotation origin is in the center I want the rotation origin to be at the bottom. 现在,看起来旋转原点在中心,我希望旋转原点在底部。 The stick should rotate when the mouse moves and when the mouse is aligned with the top of the stick. 当鼠标移动并且鼠标与操纵杆顶部对齐时,操纵杆应旋转。 It should look something like this (rotate-origin is at the bottom) 它应该看起来像这样 (旋转起点在底部)

Javascript: 使用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: HTML:

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

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

The most important part is to reset the center of rotation. 最重要的部分是重设旋转中心。 Add to CSS .stick 添加到CSS .stick

transform-origin: 50% 100%;

to have the middle of the bottom as rotation center. 以底部的中间为旋转中心。 Now you need to adapt the angle computation to be relative to this new center. 现在,您需要调整角度计算以使其相对于此新中心。 Add new variables 添加新变量

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

and change the angle computation to 并将角度计算更改为

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

Or to not have multiple sources for the same quantity, and the center at a 9:1 split: 或者没有相同数量的多个来源,并且中心以9:1的比例分割:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM