如何获取 ThreeJS 网格对象的可见宽度和高度(以像素为单位)

Kre*_*naj 5 javascript three.js

我面临着以像素为单位计算 ThreeJS 网格对象的可见视图宽度和高度的挑战。

在下面的屏幕截图中,您可以看到漂浮在 3D 空间中的对象,单击鼠标时我需要能够计算出它们占用的视图宽度和高度(以像素为单位) 在此输入图像描述

由于我对 ThreeJS 相当陌生,所以我花了很长时间才找到解决方案,所以我欢迎任何形式的帮助。

下面的函数显示了我一直在尝试的方法。

getObjectSizeInViewSpace(object){
      const size = new THREE.Vector3()
      const box = new THREE.Box3().setFromObject(object).getSize(size)
      size.project(this.camera)

      let halfWidth = window.innerWidth / 2;
      let halfHeight = window.innerHeight / 2;

      size.x = (size.x*halfWidth)
      size.y = (size.y*halfHeight)
      
      return new THREE.Vector2(size.x,size.y)
  }
Run Code Online (Sandbox Code Playgroud)

Mar*_*zzo 5

您正在寻找Vector3.project()。这基本上采用世界空间 (3D) 坐标,并使用相机的视口转换为标准化设备坐标,其范围为[-1, 1]. 例如x: -1屏幕的左侧是,x: 1右侧是。因此,您必须采用平面的 4 个向量(左上、右上、左下、右下)来计算它们在浏览器中的像素尺寸:

// Get 3D positions of top left corner (assuming they're not rotated)
vec3 topLeft = new Vector3(
    plane.position.x - planeWidth / 2, 
    plane.position.y - planeHeight / 2,
    plane.positon.z
);

// This converts x, y, z to the [-1, 1] range
topLeft.project(camera);

// This converts from [-1, 1] to [0, windowWidth]
const topLeftX = (1 + topLeft.x) / 2 * window.innerWidth;
const topLeftY = (1 - topLeft.y) / 2 * window.innerHeight;
Run Code Online (Sandbox Code Playgroud)

请注意,该topLeftY值是反转的,因为-y在 3D 空间中采用+y像素坐标。执行此操作 4 次(每个角各一次),然后减去(右 - 左)即可得到宽度,同样的方法也可得到高度。