Skip to content

Instantly share code, notes, and snippets.

@scudelletti
Created November 3, 2012 03:50
Show Gist options
  • Save scudelletti/4005763 to your computer and use it in GitHub Desktop.
Save scudelletti/4005763 to your computer and use it in GitHub Desktop.
JavaScript look to mouse
#box {
background-color: #cccccc;
left: 50%;
line-height: 3em;
height: 50px;
margin: -25px 0 0 -25px;
position: absolute;
text-align: center;
top: 50%;
width: 50px;
}​
<div id="box"></div>
var $box = $('#box');
$(document).mousemove(function(event) {
var x, y, boxCenterX, boxCenterY, radians, angle;
// Helper to convert radians to degrees
function radToDeg(radians) {
return (radians * 180 / Math.PI);
}
// Calculate the center of the object
boxCenterX = $box.offset().left + $box.width() / 2;
boxCenterY = $box.offset().top + $box.height() / 2;
// Calulate the triangle dimensions
x = event.pageX - boxCenterX;
y = boxCenterY - event.pageY;
// Find the angle in radians
radians = Math.atan(y / x);
// Correct the angle by quadrant
if (event.pageX < boxCenterX && boxCenterY > event.pageY) radians += Math.PI;
if (event.pageX < boxCenterX && boxCenterY < event.pageY) radians += Math.PI;
if (event.pageX > boxCenterX && boxCenterY < event.pageY) radians += Math.PI * 2;
// Convert the angles to degress without precision
angle = radToDeg(radians).toFixed(0);
// Convert the given angle to a cardinal direction and their intermediates
function angleToCardinal(angle) {
if (angle > 345 || angle < 015) return "L";
if (angle > 015 && angle < 075) return "NL";
if (angle > 075 && angle < 105) return "N";
if (angle > 105 && angle < 165) return "NO";
if (angle > 165 && angle < 195) return "O";
if (angle > 195 && angle < 255) return "SO";
if (angle > 255 && angle < 285) return "S";
if (angle > 285 && angle < 345) return "SL";
}
// Show the cardinal direction
$box.html(angleToCardinal(angle));
});​
@vitaliykoreev
Copy link

Thank you !:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment