-
Notifications
You must be signed in to change notification settings - Fork 0
/
magnet.js
35 lines (30 loc) · 937 Bytes
/
magnet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function magneticButton(element) {
const children = element.children[0]
element.addEventListener('mousemove', e => {
const { offsetLeft, offsetTop, offsetWidth, offsetHeight } = element
const left = e.pageX - offsetLeft
const top = e.pageY - offsetTop
const centerX = left - offsetWidth / 2
const centerY = top - offsetHeight / 2
const d = Math.sqrt(centerX**2 + centerY**2)
gsap.to(element, 0.5, {
x: centerX / 1.5,
y: centerY / 1.5,
ease: Elastic.easeOut
})
children.style.transform = `
translate3d(${centerX / 4}px, ${centerY / 4}px, 0)
rotate3d(${-centerY / 100}, ${centerX / 100}, 0, ${d / 10}deg)
`
})
element.addEventListener('mouseleave', () => {
gsap.to(element, 1.2, {
x: 0,
y: 0,
ease: Elastic.easeOut.config(1, 0.1)
})
children.style.transform = ''
})
}
const a = document.querySelector('a')
magneticButton(a)