You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

制作鼠标跟随动画眼球时,眼球与鼠标方向相反的JS问题求助

解决眼球跟随鼠标方向相反的问题

参照YouTube教程制作可跟随鼠标移动的动画眼球,但最终实现的眼球与鼠标方向相反。最初因遗漏写入script type="text/javascript"导致卡顿,完成代码后仍存在方向相反的问题。推测是数学计算环节出错,但首次接触JavaScript,无法定位问题。相关代码如下:

document.querySelector('body').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)"
});
}

问题定位与修复

  • 核心错误:Math.atan2参数顺序颠倒
    Math.atan2()的标准用法是Math.atan2(垂直差值, 水平差值),也就是先传y轴方向的差值,再传x轴的。你当前代码里写反了参数,导致计算出的角度完全反向,这就是眼球和鼠标方向相反的原因。
  • 额外优化:规范获取事件对象
    不要直接使用全局event变量,应该从回调函数的参数中接收,避免兼容性和作用域问题。
  • 简化旋转计算
    参数修正后,不需要额外的*-1 +270偏移,直接将弧度转换为角度即可。

修正后的代码

document.querySelector('body').addEventListener('mousemove', eyeball);
function eyeball(event) {
    const eyes = document.querySelectorAll('.eye');
    eyes.forEach(function(eye) {
        const eyeCenterX = eye.getBoundingClientRect().left + eye.clientWidth / 2;
        const eyeCenterY = eye.getBoundingClientRect().top + eye.clientHeight / 2;
        // 正确的参数顺序:y差值在前,x差值在后
        const radian = Math.atan2(event.pageY - eyeCenterY, event.pageX - eyeCenterX);
        // 弧度转角度,直接用于旋转
        const rotation = radian * (180 / Math.PI);
        eye.style.transform = `rotate(${rotation}deg)`;
    });
}

内容的提问来源于stack exchange,提问作者FordGT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:22:56