You need to enable JavaScript to run this app. Three.js中检测被球体遮挡的网格可见性并控制关联HTMLElement显隐
优惠活动
大模型
产品
解决方案
定价
更多

Three.js中检测被球体遮挡的网格可见性并控制关联HTMLElement显隐

Three.js 地球仪点位遮挡检测与标签显隐实现

问题场景

我有一个Three.js场景,其中包含代表地球仪的Object3D对象,以及多个代表地球仪上点位的Mesh网格元素,使用OrbitControls实现交互操作,同时为每个点位绑定了对应的HTMLElement标签。由于地球仪本质是球体,当点位位于球体背向相机的一侧时,会被球体遮挡对相机不可见。

需要实现:检测点位网格是否对相机可见、是否被物体遮挡,从而根据网格的可见性控制对应HTMLElement的显隐。HTMLElement的位置是在渲染阶段更新的,因此可见性检测也需要在渲染流程中执行,基础渲染代码如下:

private render() {
   this.renderer.render(this.scene, this.camera);

   this.points.forEach(({ label, mesh }) => {
      const screen = this.toScreenPosition(mesh);
      label.style.transform = `translate3d(${screen.x - 15}px, ${screen.y}px, 0)`;
   });

   this.requestId = window.requestAnimationFrame(this.render.bind(this));
}

实现方案

核心逻辑

通过Three.js的射线检测能力判断点位是否被遮挡:从相机位置向目标点位发射射线,若射线第一个碰撞到的3D对象就是目标点位网格,说明点位没有被遮挡,否则表示点位位于球体背面或者被其他物体遮挡。

可运行代码

直接将检测逻辑嵌入原有渲染循环的点位遍历逻辑中即可,代码如下:

this.points.forEach(({ label, mesh }) => {
    const screen = this.toScreenPosition(mesh);
    label.style.transform = `translate3d(${screen.x - 15}px, ${screen.y}px, 0)`;

    const direction = new Vector3();
    direction.copy(mesh.position).sub(this.camera.position).normalize();
    this.raycaster.set(this.camera.position, direction);
    const intersections = this.raycaster.intersectObject(this.scene, true);
    const intersected = intersections.length > 0 ? intersections[0].object.uuid === mesh.uuid : false;

    if (intersected && label.style.opacity === "0") {
        label.style.opacity = "1";
    } else if (!intersected && label.style.opacity === "1") {
        label.style.opacity = "0";
    }
});

优化提示

如果点位数量较多,可复用Vector3实例避免每帧重复创建对象,减少GC开销。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 16:57:02