我如何让这个div从它的一端旋转而不是它的中心使用atan2() [英] How do I get this div to rotate from one of its end and not its center using atan2()

查看:104
本文介绍了我如何让这个div从它的一端旋转而不是它的中心使用atan2()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I don't want the div.stick in the code below to be rotating according to the center of the 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;
}


推荐答案

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

The most important part is to reset the center of rotation. Add to 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;






或者没有相同数量的多个来源,以9:1分割的中心:


Or to not have multiple sources for the same quantity, and the center at a 9:1 split:

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

这篇关于我如何让这个div从它的一端旋转而不是它的中心使用atan2()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆