前言
你有没有见过那种超有意思的网页,上面的眼睛会跟着你的鼠标转?就像真的有人在盯着你看一样!看到实际的效果,我就跃跃欲试,看看这个是如何实现的。
话不多说,我们先看一下效果:

1. 核心思路
如果要实现这个效果,核心思路在于:当鼠标移动时,需要计算鼠标位置和每个眼球中心之间的角度,根据计算的角度,对眼球进行旋转。
2. 具体实现
具体实现步骤如下:
2.1 创建眼球结构
首先,我们需要创建基本的HTML结构,包括两个眼睛:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Eye Ball Move on Mousemove</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: radial-gradient(#f2761e, #ef4921);
}
.box {
display: flex;
}
.box .eye {
position: relative;
width: 120px;
height: 120px;
display: block;
background: #fff;
margin: 0 20px;
border-radius: 50%;
box-shadow: 0 5px 45px rgba(0,0,0,0.2),
inset 0 0 15px #f2761e,
inset 0 0 25px #f2761e;
}
.box .eye::before {
content: '';
position: absolute;
top: 50%;
left: 35%;
transform: translate(-50%,-50%);
width: 45px;
height: 45px;
border-radius: 50%;
background: #000000;
border: 10px solid #2196f3;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="box">
<div class="eye"></div>
<div class="eye"></div>
</div>
</body>
</html>
html结构主要创建眼球,使用::before伪元素创建眼球中的瞳孔,瞳孔初始位置设置在眼球的左侧(left: 35%)。
2.2 监听鼠标事件,计算角度,眼球旋转
当鼠标移动时,需要计算鼠标位置与每个眼球中心之间的角度(使用Math.atan2()函数计算鼠标位置与眼球中心形成的角度)。
根据计算出的角度,使用CSS的transform属性对眼球进行旋转,使瞳孔"看向"鼠标位置。
javascript
document.querySelector('body').addEventListener('mousemove', eyeball);
function eyeball(e) {
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(e.pageX-x, e.pageY-y);
// 将弧度转换为角度,并调整方向和偏移
let rotation = (radian*(180/Math.PI)*-1) + 270;
// 应用旋转变换
eye.style.transform = "rotate(" + rotation + "deg)";
});
}
其中最核心的代码就是
- 计算眼球中心坐标 :
getBoundingClientRect().left获取眼球元素左边缘相对于视口的位置clientWidth/2计算眼球的水平中心点- 同理计算垂直方向的中心点
- 计算角度 :
Math.atan2(e.pageX-x, e.pageY-y)计算鼠标位置与眼球中心之间的角度(弧度)radian*(180/Math.PI)将弧度转换为角度*-1反转角度方向+270调整初始角度偏移
- 眼球旋转 :使用CSS的
transform: rotate()属性将计算出的角度应用到眼球元素上。
3. 总结
最后总结一下:效果很酷炫,实现很巧妙,实际上就是运用 Math.atan2()算出鼠标在哪个方向眼球应该旋转的角度,旋转眼球的角度即可。