I am trying to create an effect where the mouse aligns with the top of a div and the div rotates as the mouse moves. The rotation should happen when the top part of the div is in line with the mouse cursor. My goal is to achieve this using the atan2
function. I envision the end result to be similar to the example found here.
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>