3D对象的2D边界框

3D对象的2D边界框

本文介绍了ThreeJS 3D对象的2D边界框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要弄清楚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边界框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 08:46