jack blank
jack blank

Reputation: 5195

Rotate a div towards the direction of the mouse using atan2()

I would like the mouse to align with the top of the div and the div should rotate when the mouse moves with the top part of the div aligned with the mouse. I want to use atan2. It should look something like this.

Javascript:

$(function() {
    var stick = $(".stick"), sHeight = stick.outerHeight(), 
                sWidth = stick.outerWidth(), atan,
                sTop = stick.offset().top, sLeft = stick.offset().left;

    $(document).on("mousemove", function(e) {
        // console.log(e.pageX, " ", e.pageY)
        atan = Math.atan2(e.pageY - sTop , e.pageX - sLeft ) 
        console.log(atan)
        stick.css({"transform" : "rotate("  + atan +  "rad)"} )
    })
})

css:

.wrapper{
    width: 500px;
    height: 400px;
    position: relative;
    border:1px solid green;
}
.stick{
    width: 3px;
    height: 200px;
    position: absolute;
    left: 50%;
    top: 50%;
    background: green;
    transform: rotate(90deg);
}

HTML:

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

Upvotes: 3

Views: 1785

Answers (2)

Lutz Lehmann
Lutz Lehmann

Reputation: 25992

The problem is that the angle computation phi=atan2(y,x) assumes a "normal" Cartesian coordinate system where the y axis points upwards. In screen coordinates, it points downwards. Thus you should use phi=atan2(-y,x).

But to be sure you should try out and report where the bar points to when using rotations 0deg and 90deg. With your code the rotation center is the middle of the bar, so orientation is difficult to determine, but it seems that 0deg points upwards and angles are applied clockwise. Thus for the inner coordinate system, where 0° is the X axis and 90° the Y axis, X = centery-y and Y=x-centerx, thus

angle = atan2(x-centerx, centery-y)

Upvotes: 0

sje397
sje397

Reputation: 41812

I made something that works here.

It seems you're not centring properly - you need to take into account the width of the div and the centre point of the container

div.$(function(){

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

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


    });
});

(I also removed the rotation in the css, and positioned the stick in the centre.)

Upvotes: 3

Related Questions