Reputation: 5195
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:
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:
<div class="display"></div>
<div class="wrapper">
<div class="stick"></div>
</div>
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;
}
Upvotes: 1
Views: 89
Reputation: 25992
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;
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;
Upvotes: 1