How do I make the eyes follow the object?

Viewed 365

Im not entirely sure what's wrong with my code. The eyes (iris) seem to be locked on the bottom right corner of the eyes and are rotating around on that fixed position. I've looked at tutorials online and tried variety of codes, but none seem to work. The end goal that I would like to achieve is to have the eyes follow the given block.

Thank you in advance!

window.addEventListener('mousemove', eyeball);
function eyeball() {
  const eye = document.querySelectorAll('.eye');
  eye.forEach(function(eye){
    let x = (eye.getBoundingClientRect().left) + (eye.clientWidth / 2);
    let y = (eye.getBoundingClientRect().top) + (eye.clientHeight / 2);

    let radian = Math.atan2(event.pageX - x, event.pageY - y);
    let rotation = (radian * (180 / Math.PI) * -1) + 270;
    eye.style.transform = "rotate("+rotation+"deg)";
  });
} 
.eye-container {
  position: absolute;
  display: flex;
  justify-content: center;
  width: 100%;
  margin-top: 20px;
  background: pink;
}

.eyeball{
  position: relative;
  width: 100px;
  height: 90px;
  border-radius: 50%;
  background: white;
  margin-right: 20px;
  box-shadow: inset 0 0 5px black;
  overflow: hidden;
}

.pupil{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 50px;
  height: 45px;
  border-radius: 50%;
  background: black;
  border: 10px solid purple;
  box-sizing: border-box;
}

.block{
  position: absolute;
  top: 50%;
  width: 100px;
  height: 100px;
  background: red;
}
<section class="eye-container">
  <div class="eyelids eyelid-left"></div>
  <div class="eyelids eyelid-right"></div>
  <div class=" eyeball left-eye">
    <div class=" eye pupil left-pupil"></div>
  </div>
  <div class="eyeball right-eye">
    <div class="eye pupil right-pupil"></div>
  </div>
</section>

<div class="block"></div>

1 Answers

What you want is probably something more like this. This will translate the pupils into place, giving it that "following look".

function eyeball(target_x, target_y) {
  const eye = document.querySelectorAll('.eye');
  eye.forEach(function(eye){
    let x = (eye.getBoundingClientRect().left) + (eye.clientWidth / 2);
    let y = (eye.getBoundingClientRect().top) + (eye.clientHeight / 2);
    let radian = Math.atan2(target_x - x, target_y - y);
    let transform_x = Math.round(Math.sin(radian) * 100);
    let transform_y = Math.round(Math.cos(radian) * 100);
    eye.style.transform = "translate(" + transform_x + "%, " + transform_y + "%)";
  });
}

You will also need to change the initial style of the pupils to get a correct offset for the position change.

.pupil{
  margin-left: 25px;
  margin-top: 25px;
  width: 50px;
  height: 45px;
  border-radius: 50%;
  background: black;
  border: 10px solid purple;
  box-sizing: border-box;
}
Related