Created
October 28, 2019 13:19
-
-
Save jeangontijo/1ef8fb3900055eeca697301a8e3e8c4d to your computer and use it in GitHub Desktop.
Follow Mouse (Translate and Rotate)
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
var el = document.querySelector(".element"); | |
var elX = el.getBoundingClientRect().x + el.offsetWidth / 2; | |
var elY = el.getBoundingClientRect().y + el.offsetHeight / 2; | |
function followMouse(e) { | |
var moveX = e.clientX - elX; | |
var moveY = e.clientY - elY; | |
var radians = Math.atan2(moveY, moveX); | |
var degrees = (radians * (180 / Math.PI)); | |
requestAnimationFrame(update.bind(update,moveX, moveY, degrees)); | |
} | |
function update(moveX, moveY, deg) { | |
el.style.transform = `translate(${moveX}px, ${moveY}px) rotate(${deg}deg)`; | |
} | |
document.addEventListener("mousemove", function(e) { | |
followMouse(e); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment