问题
I display with Three.js a scene of size 700x700. In this scene, I generate a system of particles with random positions between -250 and 250 (for x,y,z), so the box is 500x500 size.
to compute the right distance of camera (for an adapted full view of the box), I tried :
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, stats;
var camera, controls, scene, renderer;
var cross;
var width = 700, height = 700;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 60, width / height, 1, 1000 );
// tan(pi/6) = 1/sqrt(3) = height/2 / distance_z
camera.position.z = 250*Math.sqrt(3);
...
for(var p = 0; p < particleCount; p++) {
// create a particle with random
// position values, -250 -> 250
var pX = 250 - Math.random() * 500;
var pY = 250 - Math.random() * 500;
var pZ = 250 - Math.random() * 500;
var particle = new THREE.Vector3(pX, pY, pZ);
// add it to the geometry
geometry.vertices.push(particle);
}
function onWindowResize() {
camera.aspect = width /height;
camera.updateProjectionMatrix();
renderer.setSize( width, height );
controls.handleResize();
}
...
</script>
As you can see, I applied this formula for field of view (FOV)
tan(FOV/2) == height/2 / distance_z
which gives here : distance_z = 250 * sqrt(3)
but when I load the page, the zoom seems to be too high, in a way that I am too near from the 500x500 box.
Why this calculation is not correct in my case ? and How can I have a full view exactly adapted to the size of my 500x500 box ?
Maybe I do a confusion between the size of the scene and the size of my box
Thanks
回答1:
You want to compute the camera position so you get a full view of a box.
As explained in this post, you can calculate the visible height given the distance from the camera like so:
var vFOV = camera.fov * Math.PI / 180; // convert vertical fov to radians
var height = 2 * Math.tan( vFOV / 2 ) * dist; // visible height
What is important is the visibility of the front face of the cube.
In your case, the front face has height 500, and since the cube is centered at the origin, the front face of the cube is located at a distance of 250 in front of the origin. So, rewriting the formula above,
var dist = 500 / ( 2 * Math.tan( camera.fov * Math.PI / 360 ) );
Since the camera must be set back from the front face,
camera.position.set( 0, 0, 250 + dist );
This is the exact solution to make the cube "fit" in the visible height. From there, you can adjust the camera position to your liking. Alternatively, you could ensure a margin by using a slightly larger value for height
in the formula above.
three.js r.71
来源:https://stackoverflow.com/questions/31768185/three-js-good-z-distance-of-camera-for-full-view-of-box