如果鼠标位于浏览器外部,Three.js平面将被隐藏

Three.js plane is hidden if the mouse is outside the browser

本文关键字:平面 js 隐藏 Three 鼠标 浏览器 外部 如果      更新时间:2023-09-26

我是three.js的新手,我做了一个介绍,但我有一个奇怪的问题。当鼠标位于内容外部时(例如,我重新加载页面,光标位于浏览器的重新加载按钮上或浏览器外部),对象不可见。有人能提出问题出在哪里吗。

问题是运行render()时未定义mouseXmouseY。您正在将旋转绑定到鼠标,但是由于尚未进入屏幕,mouseX和mouseY仍然未定义。

function render() {
    ....
    mesh4.rotation.x = mouseY;  //undefined here
    mesh4.rotation.y = mouseX;  //undefined here
    ...
}

只有在onDocumentMouseMove()上,您才会给mouseX和mouseY一个值

function onDocumentMouseMove( event ) { 
    var windowHalfX = window.innerWidth/2;
    var windowHalfY = window.innerHeight;
    mouseX = ( event.clientX - windowHalfX ) / 11000; // <-- gets a value here
    mouseY = ( event.clientY - windowHalfY ) / 11000; // <-- and here
}

解决方案是在init()上将两个变量都设置为0,这样在运行render()函数时它们就不会被定义。

function init() {
    mouseX = 0;
    mouseY = 0;
    ...
}

以下是jsfiddle:https://jsfiddle.net/L6c8dhxd/3/

我希望这能有所帮助。