Skip to content

Instantly share code, notes, and snippets.

@basith374
Last active May 6, 2021 04:26
Show Gist options
  • Save basith374/552af7e032544fcad237f7a0f9f98f79 to your computer and use it in GitHub Desktop.
Save basith374/552af7e032544fcad237f7a0f9f98f79 to your computer and use it in GitHub Desktop.
parallax
import React, { useRef, useEffect } from 'react'
const MARGIN = 100
const STEP = 0.2
export default function Parallax({ images }) {
const refs = useRef({})
const parent = useRef()
useEffect(() => {
for (const i in refs.current) {
const el = refs.current[i]
el.style.width = el.offsetWidth + MARGIN + 'px'
el.style.height = el.offsetHeight + MARGIN + 'px'
el.style.left = -(MARGIN / 2) + 'px'
el.style.top = -(MARGIN / 2) + 'px'
}
}, [])
function onMouseMove({ clientX, clientY, target }) {
const width = target.offsetWidth
const height = target.offsetHeight
const left = ((clientX - parent.current.offsetLeft) / width) * MARGIN
const top = ((clientY - parent.current.offsetTop) / height) * MARGIN
for (let i = 0; i < Object.keys(refs.current).length; i++) {
const el = refs.current[i]
const ratio = STEP * 10 * (i + 1) / 10
el.style.left = ratio * (left - MARGIN) + 'px'
el.style.top = ratio * (top - MARGIN) + 'px'
}
}
return (
<div className={styles.container} ref={parent} onMouseMove={onMouseMove}>
{images.map((f, k) => (
<img
ref={(ref) => {
refs.current[k] = ref
}}
src={f}
key={k}
/>
))}
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment