如何使用 OrthographicCamera 在 Threejs 中使对象适合相机?

Sta*_*n.X 2 three.js

我找到了很多解决方案,但它只能适用于 PerspectiveCamera,因为 OrthographicCamera 没有 fov。有什么解决办法吗?

nid*_*res 5

正如@gaitat所说,THREE.OrthographicCamera您需要调整它的视锥体尺寸以适合您想要放大的对象的大小。

简单的做法是使用geometry.boundingSphere和设置相机topleftbottomup以此为基础。更容易做的事情是使用camera.zoom来完成工作,即

// center camera on the object (ellipse in this case)
var boundingSphere = ellipse.geometry.boundingSphere

// aspect equals window.innerWidth / window.innerHeight
if( aspect > 1.0 )
{
    // if view is wider than it is tall, zoom to fit height
    camera.zoom = viewHeight / ( boundingSphere.radius * 2 )
}
else
{
    // if view is taller than it is wide, zoom to fit width
    camera.zoom = viewWidth / ( boundingSphere.radius * 2 )
}

// Don't forget this
camera.updateProjectionMatrix()
Run Code Online (Sandbox Code Playgroud)

这会将缩放级别设置为使对象(在本例中为椭圆)完全适合相机的截锥体。

但是,您还必须通过以下任一方式将相机置于对象的中心:

  • 旋转相机以指向boundingSphere中心
  • 平移相机,使boundingSphere中心最终位于相机的截锥体轴上

由于平移相机是两者中更容易做的事情,并且THREE.OrthographicCamera主要用于显示场景的 2D 表示(即用于 UI 或发生在与相机平行的平面上的其他一些事情),因此以下是要做的代码只是:

camera.position.copy(boundingSphere.center)
// The number here is more or less arbitrary
// as long as all objects that need to be visible
// end up within the frustum
camera.position.z = 15
Run Code Online (Sandbox Code Playgroud)

这假设您的对象位于与 XY 平面平行的某个平面中,并且相机的位置看起来与 Z 轴平行(默认情况下)。

这是 codepen,显示 XY 平面中的小网格和椭圆。鼠标按下时相机将缩放到椭圆形,鼠标按下时相机将恢复到原始状态:

https://codepen.io/anon/pen/aJEzew