Skip to content

Instantly share code, notes, and snippets.

@Corjen
Created May 23, 2017 07:17
Show Gist options
  • Save Corjen/7358f74dcd2cd8f4580b2fec64edeb29 to your computer and use it in GitHub Desktop.
Save Corjen/7358f74dcd2cd8f4580b2fec64edeb29 to your computer and use it in GitHub Desktop.
import anime from 'animejs'
const animatePerspective = () => {
const items = [...document.querySelectorAll('.js-animate-perspective')]
if (!items || typeof window.requestAnimationFrame === 'undefined') return
// Cache elements
const elements = {}
items.forEach(item => {
elements[item.id] = {
parent: item,
content: item.querySelector('.c-challenge-card__content-container'),
shine: item.querySelector('.c-challenge-card__shine')
}
})
items.forEach(item => {
item.addEventListener('mousemove', function (e) {
window.requestAnimationFrame(() => {
const { parent, content, shine } = elements[this.id]
const mousepos = getMousePos(e)
const docScrolls = {left: document.body.scrollLeft + document.documentElement.scrollLeft, top: document.body.scrollTop + document.documentElement.scrollTop}
const bounds = parent.getBoundingClientRect()
const relativeMousePosition = { x: mousepos.x - bounds.left - docScrolls.left, y: mousepos.y - bounds.top - docScrolls.top }
const rotations = {
x: ((bounds.height / 2) - relativeMousePosition.y) * 0.03,
y: (relativeMousePosition.x - (bounds.width / 2)) * 0.04
}
const translations = {
x: (relativeMousePosition.x - (bounds.width / 2)) * 0.1,
y: (relativeMousePosition.y - (bounds.height / 2)) * 0.1
}
rotate(parent, rotations.x, rotations.y)
translate(content, translations.x, translations.y)
translate(shine, translations.x, translations.y)
})
})
item.addEventListener('mouseleave', function (e) {
window.requestAnimationFrame(() => {
const { parent, content, shine } = elements[this.id]
anime.remove(parent)
anime.remove(content)
anime.remove(shine)
rotate(parent, 0, 0)
translate(content, 0, 0)
translate(shine, 0, 0)
})
})
})
const rotate = (el, rotateX, rotateY) => {
anime({
targets: el,
reverseAnimation: {
duration: 1200,
easing: 'easeOutElastic'
},
rotateX,
rotateY,
rotateZ: 0
})
}
const translate = (el, translateX, translateY) => {
anime({
targets: el,
reverseAnimation: {
duration: 1200,
easing: 'easeOutElastic'
},
translateX,
translateY,
translateZ: 0
})
}
const getMousePos = (e) => {
let posx = 0
let posy = 0
if (e.pageX || e.pageY) {
posx = e.pageX
posy = e.pageY
} else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop
}
return { x: posx, y: posy }
}
}
export default animatePerspective
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment