问题描述
我需要弄清楚我的 3D 对象在屏幕上使用的区域.
I need figure out the area on screen which my 3D object uses.
我尝试通过 Google 寻找答案,但没有成功.
I've tried to Google for an answer but with no success.
函数 geometry.computeBoundingBox()
只返回 3D 边界框.
The function geometry.computeBoundingBox()
is only returning the 3D bounding box.
如何将其转换为 2D 边界框?
How could I convert this to a 2D bounding box?
推荐答案
您只需将所有顶点转换为屏幕空间,并从它们制作一个 2D 边界框:
You simply have to convert all vertices to screen space and make a 2D bounding box from them:
function computeScreenSpaceBoundingBox(mesh, camera) {
var vertices = mesh.geometry.vertices;
var vertex = new THREE.Vector3();
var min = new THREE.Vector3(1, 1, 1);
var max = new THREE.Vector3(-1, -1, -1);
for (var i = 0; i < vertices.length; i++) {
var vertexWorldCoord = vertex.copy(vertices[i]).applyMatrix4(mesh.matrixWorld);
var vertexScreenSpace = vertexWorldCoord.project(camera);
min.min(vertexScreenSpace);
max.max(vertexScreenSpace);
}
return new THREE.Box2(min, max);
}
生成的 Box2 位于标准化屏幕坐标 [-1, 1] 中.您可以通过乘以渲染器的高度和宽度的一半来获得像素:
The resulting Box2 is in normalized screen coordinates [-1, 1]. You can get the pixels by multiplying with half of the height and width of your renderer:
function normalizedToPixels(coord, renderWidthPixels, renderHeightPixels) {
var halfScreen = new THREE.Vector2(renderWidthPixels/2, renderHeightPixels/2)
return coord.clone().multiply(halfScreen);
}
在此处查看演示:http://jsfiddle.net/holgerl/6fy9d54t/
根据@WestLangley 的建议减少了内循环中的内存使用
Reduced memory usage in inner loop by suggestion from @WestLangley
修复了@manthrax 发现的错误
Fixed a bug discovered by @manthrax
这篇关于ThreeJS 3D 对象的 2D 边界框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!