Threejs -camera

by black strings

HTML

<script src="https://rawgit.com/mrdoob/three.js/dev/build/three.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/dev/examples/js/controls/OrbitControls.js"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/controls/OrbitControls.js"></script>

CSS

/* fix mouse click offset errors when doing drags */
body {
  margin: 0;
}

#scene {
  width: 65%;
  float: right;
  display: inline-block;
}

JavaScript

var scene, renderer, camera;
var cube;
var controls;

init();
lightSetup();
animate();

function init() {
  renderer = new THREE.WebGLRenderer({
    antialias: true
  });
  var width = window.innerWidth;
  var height = window.innerHeight;
  renderer.setSize(width, height);
  document.body.appendChild(renderer.domElement);

  scene = new THREE.Scene();

  camera = new THREE.PerspectiveCamera(45, width / height, 1, 1000);

  controls = new THREE.OrbitControls(camera, renderer.domElement);

  lightSetup();
  
  const geometry = new THREE.BoxGeometry( 1, 1, 1 );
	
  const material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
	
  const cube = new THREE.Mesh( geometry, material );
  
  cube.name = "block";
	
  scene.add( cube );
  
  fitCameraToMeshType("block");
  
  controls.minDistance = 3;
}


function animate() {
  controls.update();
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}

function lightSetup() {
  if (scene) {
    var dirLight = new THREE.DirectionalLight();
    dirLight.position.set(3, 2, 1);
    dirLight.position.multiplyScalar(10);
    scene.add(dirLight);
  }

}

/**
	 * Fit the camera to the mesh type
	 */
	function fitCameraToMeshType(name) {
		if(scene) {
			if(scene.children && scene.children.length) {
				if(camera) {
					if(controls) {
						camera.position.z = 400;

						camera.lookAt(new THREE.Vector3());

						const fitOffset = 3;

						const box = new THREE.Box3();

						scene.children.forEach((mesh) => {
							if(mesh.name === name) {
								box.expandByObject(mesh);
							}
						});

						const size = new THREE.Vector3();

						const center = new THREE.Vector3();

						box.getSize(size);

						box.getCenter(center);

						const maxSize = Math.max(size.x, size.y, size.z);

						const fitHeightDistance = maxSize / ( 3 * Math.atan( Math.PI * camera.fov / 360 ) );

						const fitWidthDistance = fitHeightDistance / camera.aspect;

						const distance = fitOffset * Math.max( fitHeightDistance,...