12 AnswersNew Answer
use Math.cos(x),Math.tan(x),Math.sin(x) e.t.c...... use Pythagorean theorem and pageX,pageY & transform:rotate(90deg)………… are you good with maths?? ^_^
@visph panics when it reaches y-intercept (low values of y-axis, dunno how to fix it… /;), activates only on "move" events……
@visph I do Y/X (tangent) and multiply by "45" then if mouse is on first or third quarter i do "deg=90-deg" and if it is on second or fourth i do "deg+=90" (…a bit advanced but no other workaround /; …)
Yes! when Y/X equals to "1" this means that angle is "45"………
@visph any clue on how to fix that "panic"?? (i tried setting angle to 0 when mouse is close to Y but not working…… ~_~)
For: - C = (cx,cy) center of the element to rotate - M = (mx,my) mouse position - ra rotation angle of element, with 0 toward up We need to calculate the angle between the vector up U (0,n) and the vector V formed by segment CM ( direction is important )... V = (vx,vy) = (mx-cx,my-cy) ... and we keep only unit vectors, so we need calculate length vl of V: vl = squareRootOf((mx-cx)²+(my-cy)²) V'(vx',vy') = (vx/vl,vy/vl) Maths, and mainly geometry tell that ( remember that we rotated the trigonometric circle of 90° ): cos(ra) = vy' ... and sign of vx' give sign of angle 'ra', so: ra = (vx'/vx')*arcCos(vy') <=> (vx/vx)*arcCos(vy/vl) <=> signOf(mx-cx)*arcCos((my-cy)/squareRootOf((mx-cx)²+(my-cy)²)) In JS built-in functions, we have: var s = Math.sign(n); // return -1, 1, 0, -0 or NaN var a = Math.acos(n); // for n in [-1;1] return arccosine in radian ( a in [0;π] ) var r = Math.sqrt(n); // return square root of n So: var cx,cy,mx,my; // here you must assign particular values ^^ var vx=mx-cx; var s=Math.sign(vx); if (s==0) return 0; // particular case of zero angle don't need further calculation ;) // here you can also handle the error case of (s===NaN)... var vy=my-cy; var vl=Math.sqrt(vx*vx+vy*vy); var ra=s*Math.acos(vy/vl); And just use the angle 'ra' so set css property 'transform:rotate()' ( remember that's in radian, you must convert it in degree to use with css )...
@VH: Done. https://code.sololearn.com/W548FW09039Q/#html
@VH: I don't understand exactly what you do in your code ( it seems to not be as I would do, and not as you firstly suggest ), and cannot determine what make your rotating element "panic" sometimes ( quick erratic multi rotations )... Can you explain further please?
@VH Yep, but what's your algo' to derterminate/aplly the angle? You seems to consider only mouse pos' relative to viewport?
@VH: XD You're still on it ;) More readable now: I got it ^^ You cheat and approximate an angle around 45 degrees, relatively to the distant of mouse on x axis between center of viewport :P
@VH: No :( ... and I guess I would more quick implement my solution than searching to fix yours ^^