Created
March 27, 2021 21:35
-
-
Save niklasp/b751f05efcfc0859a6bb796eaa2c38a1 to your computer and use it in GitHub Desktop.
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
/** | |
* | |
* @param {DOMElement} container | |
* @param {DOMElement} element | |
* | |
* Make the element follow the mouse when it is over container, with | |
* a following speed of speed. | |
*/ | |
export function followMouse( container, element, damping ) { | |
let mouseX = 0, mouseY = 0, translateX = 0, translateY = 0; | |
function init() { | |
initListeners(); | |
rAF(); | |
} | |
function initListeners() { | |
container.addEventListener( 'mousemove', handleMouseMove ); | |
} | |
function handleMouseMove( e ) { | |
const bounds = e.currentTarget.getBoundingClientRect(); | |
mouseX = e.clientX - bounds.left; | |
mouseY = e.clientY - bounds.top; | |
} | |
function rAF() { | |
translateX += ( mouseX - translateX ) * damping; | |
translateY += ( mouseY - translateY ) * damping; | |
element.style.transform = `translate3d( ${ translateX }px, ${ translateY }px, 0)`; | |
window.requestAnimationFrame( rAF ); | |
} | |
init(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment