Javascript Code for Making Eyes Follow with CSS and HTML

Posted by

Eyes Follow in JavaScript

body {
text-align: center;
}
#container {
position: relative;
width: 300px;
height: 300px;
margin: 50px auto;
}
#eye {
width: 100px;
height: 100px;
background-color: white;
border-radius: 50%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 2px solid black;
}
#pupil {
width: 50px;
height: 50px;
background-color: black;
border-radius: 50%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

Eyes Follow in JavaScript

Move your mouse around the white circle to make the pupil follow it.

const eye = document.getElementById(‘eye’);
const pupil = document.getElementById(‘pupil’);

eye.addEventListener(‘mousemove’, (e) => {
const eyeRect = eye.getBoundingClientRect();
const eyeCenterX = eyeRect.left + eyeRect.width / 2;
const eyeCenterY = eyeRect.top + eyeRect.height / 2;

const angle = Math.atan2(e.clientY – eyeCenterY, e.clientX – eyeCenterX);
const radius = eyeRect.width / 4;

const pupilX = eyeCenterX + Math.cos(angle) * radius;
const pupilY = eyeCenterY + Math.sin(angle) * radius;

pupil.style.left = `${pupilX}px`;
pupil.style.top = `${pupilY}px`;
});

0 0 votes
Article Rating
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@ilyasthaimi2084
6 months ago

Nice

@DevWeb-mx4qo
6 months ago

Wow😮😆😆cool