Last active
February 18, 2024 17:02
-
-
Save Flyrell/2a4714255229a33ce6384ada3210d3ae to your computer and use it in GitHub Desktop.
Simple function for creating element that rotate based on the mouse position. In other words, the element is looking-at/following the mouse.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* DEMO: https://jsfiddle.net/gd6b71Ln/38/ | |
* | |
* CAUTION: You will need to edit `el.style.transform = 'rotate('+ deg +'deg)'`, | |
* in case the element has already existing transform styles (just append them) | |
* | |
* COMPATIBILITY: https://caniuse.com/#feat=getboundingclientrect | |
* https://caniuse.com/#feat=transforms2d | |
* | |
* Makes the element rotate based on the mouse position | |
* @param {HTMLElement} el - Element that is going to be rotated | |
* @return {undefined} | |
*/ | |
function followMouse (el) { | |
const position = el.getBoundingClientRect(); | |
const callback = function(event) { | |
const x = event.x - (position.x + position.width / 2); | |
const y = position.y + position.height / 2 - event.y; | |
const degrees = Math.atan(x / y) * (180 / Math.PI) + (y < 0 ? 180 : 0); | |
el.style.transform = `rotate(${degrees}deg)`; | |
}; | |
document.addEventListener('mousemove', callback, true); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment