如何使用getBoundingClientRect获得学位的轮换?

时间:2015-02-06 12:08:10

标签: javascript css

在我的游戏中,你可以点击橙色框(它应该代表一个怪物)。单击后,绿色线将附加到字符div。例如,为了更好的解释:

http://i.gyazo.com/537c8acb9881a3bfaa6f19259de37618.gif

这是我用来生成该行的代码:

l = document.createElement('div');
l.innerHTML='<div id="oLineBar" style="  transform: rotate(' + RANDOM + 'deg);" class="fadeIn2"><div id="lineBar" class="lineBarCharacter"></div></div>';
character.appendChild(l);

那个CSS就是:

.lineBarCharacter{
    height: 321px;
    width: 2px;
    background: rgba(39, 182, 0, 0.46)
}

#oLineBar {
    position: absolute;
    top: 20px;
    left: 37px;
    opacity: 1;
    transition: transform 1s linear;
    transform-origin: top left;
    transform-style: preserve-3D;
    -webkit-transition: opacity 1s;
    transition: opacity 1s;
    -ms-transition-property: opacity, -ms-transform;
}

现在,我在这里得到了橙色框getboundingClientRect:

ClientRect {height: 95, width: 88, left: 1250.5, bottom: 471, right: 1338.5…}bottom: 471height: 95left: 1250.5right: 1338.5top: 376width: 88

如何根据橙色框的位置(来自getboundingClientRect数据)确定正确的旋转度

不只是特定的橙色框,而是从getBoundingClientRect检索的任何数据。如果这是有道理的......我有点失落,如果这令人困惑,请提前抱歉。我非常希望那条线与橙色框的方向相同。

1 个答案:

答案 0 :(得分:1)

这更像是一个数学问题,而不是编程,但你应该基本上计算你的角色和目标之间的x和y差异,然后计算角度。

假设x1,y1是字符坐标,x2,y2是目标坐标:

  • (x2-x1)会给出x差异,
  • (y2-y1)会给出y差异,
  • ArcTangent ( (y2-y1) / (x2-x1))会给你弧度的角度。
  • angleInRadians * (180/pi)会给你角度。
  • 4*ArcTangent(1)会给您pi

现在使用JavaScript:

var angle = Math.round(Math.atan((y2 - y1) / (x2 - x1)) * (180 / (4 * Math.atan(1))));
  • 或者正如莫里斯建议的那样,使用Math.atan2

    var angle = Math.round(Math.atan2(y2 - y1 , x2 - x1) * (180 / (4 * Math.atan(1))));
    

以下是一个例子:

$(function () {
    $(document).on("mousemove", function (ev) {
        var x1 = 200,
            y1 = 200;
        var x2 = ev.clientX,
            y2 = ev.clientY;
        var d =  Math.sqrt(Math.pow((y2 - y1),2)+Math.pow((x2 - x1),2));
        var angle = Math.round(Math.atan2((y2 - y1) , (x2 - x1)) * (180 / (4 * Math.atan(1))));
        console.log(angle);
        $("#line").css({
            "transform":"rotate("+angle+"deg)",
            "width":d+"px"
        });
    });
});
#line {
    position:absolute;
    left:200px;
    top:200px;
    width:200px;
    height:5px;
    background:green;
    transform-origin: 0% 0%;
    transform:rotate(45deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="line"></div>

如果您使用的是移动广告,则 Fiddle