Make old school googly eyes that follows the pointing device.
Make old school googly eyes that follows the pointing device.
What a wonderful idea! Let’s create a pair of old-school googly eyes that track the user’s pointing device (e.g., their mouse pointer or touches). This will involve:
Let me assemble this for you.
<div class="eye left-eye">
<div class="pupil"></div>
</div>
<div class="eye right-eye">
<div class="pupil"></div>
</div>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background: #fbeec1;
margin: 0;
overflow: hidden;
font-family: sans-serif;
}
.eye {
width: 100px;
height: 100px;
background: white;
border: 5px solid black;
border-radius: 50%;
margin: 0 20px;
position: relative;
display: flex;
justify-content: center;
align-items: center;
}
.pupil {
width: 40px;
height: 40px;
background: black;
border-radius: 50%;
position: absolute;
}
const eyes = document.querySelectorAll('.eye');
document.addEventListener('mousemove', (event) => {
const { clientX: mouseX, clientY: mouseY } = event;
eyes.forEach(eye => {
const rect = eye.getBoundingClientRect();
const eyeCenterX = rect.left + rect.width / 2;
const eyeCenterY = rect.top + rect.height / 2;
const deltaX = mouseX - eyeCenterX;
const deltaY = mouseY - eyeCenterY;
const angle = Math.atan2(deltaY, deltaX);
const pupil = eye.querySelector('.pupil');
const eyeRadius = rect.width / 2 - pupil.offsetWidth / 2;
const pupilX = eyeRadius * Math.cos(angle);
const pupilY = eyeRadius * Math.sin(angle);
pupil.style.transform = `translate(${pupilX}px, ${pupilY}px)`;
});
});