gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:38:47 24 4
gpt4 key购买 nike

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

在下面的屏幕截图中,您可以看到对象漂浮在 3D 空间中,单击鼠标时我需要能够弄清楚它们占用的 View 宽度和高度(以像素为单位) enter image description here

由于我是 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)
}

最佳答案

您正在寻找 Vector3.project() .这基本上采用世界空间 (3D) 坐标,并使用相机的视口(viewport)转换为规范化的设备坐标,范围为 [-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;

请注意 topLeftY 值是反转的,因为 3D 空间中的 -y 在像素坐标中变为 +y。这样做 4 次(每个 Angular 一次),然后您可以减去(右 - 左)以获得宽度,高度也相同。

关于javascript - 如何以像素为单位获取ThreeJS网格对象的可见宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68854864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com