Skip to content

Instantly share code, notes, and snippets.

@jeangontijo
Created October 28, 2019 13:19
Show Gist options
  • Save jeangontijo/1ef8fb3900055eeca697301a8e3e8c4d to your computer and use it in GitHub Desktop.
Save jeangontijo/1ef8fb3900055eeca697301a8e3e8c4d to your computer and use it in GitHub Desktop.
Follow Mouse (Translate and Rotate)
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