Quantcast
Viewing latest article 1
Browse Latest Browse All 2

Answer by Banana for How do I get the rotation of degree with getBoundingClientRect?

This is more of a math question rather than programming, but you should basically calculate the x and y differences between your character and its target, and then calculate the angle.

Assuming x1,y1 are the character coordinates, and x2,y2 are the target coordinates:

  • (x2-x1) will give the x difference,
  • (y2-y1) will give the y difference,
  • ArcTangent ( (y2-y1) / (x2-x1)) will give you the angle in radians.
  • angleInRadians * (180/pi) will give you the angle in degrees.
  • 4*ArcTangent(1) will give you pi

Now in JavaScript:

var angle = Math.round(Math.atan((y2 - y1) / (x2 - x1)) * (180 / (4 * Math.atan(1))));
  • Or as Maurice suggested, use Math.atan2:

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

Here is an example:

$(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>

Here is a Fiddle if you are on mobile.


Viewing latest article 1
Browse Latest Browse All 2

Trending Articles