Skip to content

Instantly share code, notes, and snippets.

@TahaSh
Created July 7, 2024 12:13
Show Gist options
  • Save TahaSh/1c885f141576b7e1f8c3ba3169cdcdec to your computer and use it in GitHub Desktop.
Save TahaSh/1c885f141576b7e1f8c3ba3169cdcdec to your computer and use it in GitHub Desktop.
Cursor-driven animations example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Cursor-driven animations</title>
</head>
<body>
<div class="box"></div>
<script type="module" src="/main.js"></script>
</body>
</html>
import './style.css'
const box = document.querySelector('.box')
const MAX_DISTANCE = 200
function clamp(v, min, max) {
return Math.min(Math.max(v, min), max)
}
function remap(v, a, b, c, d) {
return ((v - a) / (b - a)) * (d - c) + c
}
window.addEventListener('mousemove', (e) => {
const mouseX = e.clientX
const mouseY = e.clientY
const rect = box.getBoundingClientRect()
const boxX = rect.left + rect.width / 2
const boxY = rect.top + rect.height / 2
const x = boxX - mouseX
const y = boxY - mouseY
const distance = Math.sqrt(x * x + y * y)
const progress = distance / MAX_DISTANCE
const clampedProgress = clamp(progress, 0, 1)
const inverseProgress = 1 - clampedProgress
const scale = remap(inverseProgress, 0, 1, 1, 2)
const opacity = remap(inverseProgress, 0, 1, 0.5, 1)
const rotation = remap(inverseProgress, 0, 1, 0, 360)
box.style.transform = `scale(${scale}) rotate(${rotation}deg)`
box.style.opacity = `${opacity}`
})
body {
background-color: #242424;
margin: 0;
padding: 0;
width: 100%;
min-height: 100dvh;
display: flex;
align-items: center;
justify-content: center;
}
.box {
width: 100px;
height: 100px;
background: #eee;
border-radius: 20px;
opacity: 0.5;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment