# How to dynamically adjust the camera in three js

**URL:** <https://discourse.threejs.org/t/how-to-dynamically-adjust-the-camera-in-three-js/15593>\
**Category:** Questions\
**Tags:** camera\
**Created:** [May 27, 2020, 6:33am UTC](https://discourse.threejs.org/t/how-to-dynamically-adjust-the-camera-in-three-js/15593 "2020-05-27T06:33:53Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![ThreejsNewbie](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.threejs.org/threejsnewbie/32/7975_2.png) [@ThreejsNewbie](https://discourse.threejs.org/u/ThreejsNewbie)\
**Post date:** [May 27, 2020, 6:33am UTC](https://discourse.threejs.org/t/how-to-dynamically-adjust-the-camera-in-three-js/15593/1 "2020-05-27T06:33:53Z")

</div>

Hi, i have a requirement where the mesh dimensions would change depending on the item selected by user.  
currently there are three combinations  
createwarehouse(99,99,99);

 ![image](https://canada1.discourse-cdn.com/flex035/uploads/threejs/original/2X/c/c0c1aee46cf0859566d9e85af44d4a48ce01a53b.png)

createwarehouse(30,09,30);

 ![image](https://canada1.discourse-cdn.com/flex035/uploads/threejs/original/2X/c/cc0c7db5ef3922ca02901d0360ac9298c6fed55a.png)

createwarehouse(400,99,99);

 ![image](https://canada1.discourse-cdn.com/flex035/uploads/threejs/original/2X/1/1e45448ed166e26a15fbd7173af4d786616ca502.png)

depending on the list page value these models should be displayed but currently i, not able to get this kind of view

i modified the camera code to

```
camera.position.x = - warehousex*2 ;
camera.position.y = warehousey*5;
camera.position.z = warehousez*0.5;

```

but this didnt work i could not get the above results  
below is the entire code piece

code

```
// global variables 3Dwarehousemodel

var scene,renderer; var xhttpgettoken; var xhttpupdatedetails;
var taskno;	
var access_area ;
var bin_length;
var tasknumberdetails =[];
var selectedtask = new Array();
var ze = 0;
var taskArr
var tasknoarray=[]
var putawayproducts = [];
var draggableFlag = 'N';
var rotatefunctionFlag;
var showbindetailsFlag = 'N';
var RotateFunctionFlag = 'N';
var putawayflag = 'N';
var putawayflag1 = 'N';
var hoveredObjname,hoveredObjposx,hoveredObjposy,hoveredObjposz;
var offsetvalue;
var zpostionrest,zlimitrest,secondobjectposition;
var tooltipEnabledObjects = [];
var newboxplacement = 0;
var Scalingvalue = 5;// for the model to appear enhanced(large n clear);
var objects = [];
var clock;
var canvas;
var camera;
var GoodsBoxHelper;
var bindetails = [];
var validatearrayfornewbin=[]; /*new_bin*/
var ylimit;
var colls,newlycreatedbin;
var ground; // A square base on which the cylinders stand.
var cylinder; // A cylinder that will be cloned to make the visible cylinders.
var warehousez, warehousey, warehousex;
var world, animate; 
var raycaster = new THREE.Raycaster(); // A THREE.Raycaster for user mouse input.
var mouseAction; // currently selected mouse action
var dragItem; // the cylinder that is being dragged, during a drag operation
var intersects; //the objects intersected
var plane; 

var camera, scene, projector, mouseVector, controls;
var tooltipPosition;
var mouseX, mouseY, draggable;
var pen, c_mesh, rotateObj = [], groundRaycastObj = [];
var dynamicObj = []
var mouse = new THREE.Vector2(), INTERSECTED;
var warehouselength,warehousewidth,warehouseheight;
var walls;
var mesh_box;
var outlineContainer;
var dynamicbincreationFlag; // Flag to set the pointer for creation of dynamic bins
var p;
var jsondata ;
var data;
var propertycontents;
var di,pi;
var camera, // We need a camera.
scene, // The camera has to see something.
renderer, // Render our graphics.
controls, // Our Orbit Controller for camera magic.
container, // Our HTML container for the program.
rotationPoint; // The point in which our camera will rotate around.
var characterSize = 50;
var outlineSize = characterSize * 0.05;
    // Track all objects and collisions.
var objects = [];
var collisions = [];
var positionofnewbin=[];

// Set mouse and raycaster.
var raycaster = new THREE.Raycaster();
var listpagedetails = [];
var request;
var arrPack=[];
var posttobackend = [];
var totalcolumns;
var jsondata ;
var data;
var rowcount = 0;
var propertycontents;
var di,pi,ValueFlag;
var mouse = new THREE.Vector2();
var p = 0;
var request;
var latestMouseProjection; // this is the latest projection of the mouse on object (i.e. intersection with ray)
var hoveredObj;
var tooltipDisplayTimeout;

/ ********initialize function to display the required details at the load duration****** /
	
function init() {
/*setting the close button to transparent*/

// Prepare container
container = document.createElement( 'div' );
document.body.appendChild( container );
scene = new THREE.Scene();

/ **define camera settings to adjust the entire model ni a proper viewing angle** /
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 10000 );
camera.position.x = -500;
camera.position.y = 600;
camera.position.z = 200;
camera.lookAt(camera.position.x, camera.position.y, camera.position.z);

renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setClearColor( "#e5e5e5" ); //setting a grey color on the screen
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight ); //adjusting the black screen on the browser

document.body.appendChild( renderer.domElement );
window.addEventListener( 'resize', () => {

renderer.setSize( window.innerWidth, window.innerHeight );
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix(); //today edited

} );

// Create a rotation point.
rotationPoint = new THREE.Object3D();
rotationPoint.position.set( 0, 0, 0 );
scene.add( rotationPoint );
container.appendChild( renderer.domElement );

/ *****************************************end of service call for warehouse creation*********************************************************** /
/ *****code for creation of ground surface**** /
console.log('warehousex' + warehousex);
console.log('warehousey' + warehousey);
var groundlength = 1;
var groundheight = 0;
var groundwidth = 1;
/* var groundlength = 1;
var groundheight = 0;
var groundwidth = 1;*/
var geometry = new THREE.BoxGeometry( groundlength, groundheight, groundwidth );
var material = new THREE.MeshBasicMaterial( { color: "#B5651D"} ); //B5651D
var ground = new THREE.Mesh( geometry, material );

ground.position.x = 500 ;
ground.position.z = 300 ;
ground.position.y = - 2;

groundBox = new THREE.BoxHelper( ground );
groundBox.update( ground );
scene.add( ground );

var axes = new THREE.AxesHelper( 1000 ); //to view x y z axis
scene.add( axes );

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

controls.minDistance = 1;
controls.maxDistance = 10000;
controls.target = new THREE.Vector3( 0, 0, 0 );
clock = new THREE.Clock();

THREEx.WindowResize( renderer, camera );

//createwarehouse(99,99,99);

//createwarehouse(30,09,30);
createwarehouse(400,99,99);

/*end of bin creation*/

/*code for creation of outer warehouse*/
	
function createwarehouse(warehousex,warehousey,warehousez) {

warehousex = parseInt(warehousex*Scalingvalue) +1;
warehousey = parseInt(warehousey*Scalingvalue) ;
warehousez = parseInt(warehousez*Scalingvalue) +1;
var geometry = new THREE.BoxGeometry( warehousex, warehousey, warehousez ); // length height width
var cubeMaterials = [
new THREE.MeshBasicMaterial( { color: "#A9A9A9", side: THREE.DoubleSide } ), , , // left
new THREE.MeshBasicMaterial( {color: "#A9A9A9", side: THREE.DoubleSide } ), //bottom
new THREE.MeshBasicMaterial( {color: "#A9A9A9", side: THREE.DoubleSide } ), // front
new THREE.MeshBasicMaterial( { color: "#A9A9A9", side: THREE.DoubleSide } ) // green
];

var material = new THREE.MeshFaceMaterial( cubeMaterials );
var warehouse = new THREE.Mesh( geometry, material );

warehouse.position.x = parseInt((warehousex/2)) -0.5 ;
warehouse.position.y = ( warehousey / 2 ) -0.5;
warehouse.position.z = parseInt((warehousez/2)) -0.5;
outlineContainer = new THREE.BoxHelper( warehouse,'#828282');

warehouse.add(outlineContainer);
scene.add(outlineContainer);
scene.add( warehouse );

/ ***creating a new plane for the pointer to detect the ground to create a bin on click**** /

var planegeometry = new THREE.BoxGeometry( warehousex, 0 , warehousez );
var planematerial = new THREE.MeshBasicMaterial( {color: 'orange', side: THREE.DoubleSide} );
var plane = new THREE.Mesh( planegeometry, planematerial );
plane.position.x = parseInt((warehousex/2)) -0.5 ;
plane.position.z = parseInt((warehousez/2)) -0.5;
//plane.rotation.y = -Math.PI / 4;
plane.name = 'dynamicground';
scene.add( plane );
dynamicObj.push(plane);
validatearrayfornewbin.push(plane); /*new_bin*/

ground.geometry.parameters.width = 1;
ground.geometry.parameters.depth = 1;
console.log(ground.geometry.parameters.width);
ground.scale.set( warehousex*2, 0, warehousez*5);
ground.position.x = warehouse.geometry.parameters.width/2 ;
ground.position.z = (warehouse.geometry.parameters.depth/2);

camera.position.x = - warehousex*2 ;	
camera.position.y = warehousey*5;
camera.position.z = warehousez*0.5;
}

animate();

}

function animate() {

requestAnimationFrame( animate );
controls.update();

renderer.render( scene, camera );

}

```

Can someone please help me out with this.  
how to adjust the camera such that it dynamically adjusts based on the dimensions of the mesh

Thanks

I have attached the code zip below[3Dwarehousemodel.zip](https://discourse.threejs.org/uploads/short-url/CLTplZqG85IkwsyjuHQVr9BCYj.zip) (263.4 KB)

---

<div class="post-metadata">

**Author:** ![Mugen87](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.threejs.org/mugen87/32/5645_2.png) [@Mugen87](https://discourse.threejs.org/u/Mugen87)\
**Post date:** [May 27, 2020, 7:49am UTC](https://discourse.threejs.org/t/how-to-dynamically-adjust-the-camera-in-three-js/15593/2 "2020-05-27T07:49:24Z")

</div>

One way to solve this issue is by changing camera parameters based on the bounding box of your mesh. This approach is used by viewer application like the `three.js` based [gltf-viewer](https://gltf-viewer.donmccurdy.com/). Check out the following code listing for more information:

> <https://github.com/donmccurdy/three-gltf-viewer/blob/a5fd64686f55a8cb3effd8914b2cbcca6b6cbae1/src/viewer.js#L266-L293>

The code also centers the object which is probably not required in your scene.

---

<div class="post-metadata">

**Author:** ![PrzemekP](https://avatars.discourse-cdn.com/v4/letter/p/edb3f5/32.png) [@PrzemekP](https://discourse.threejs.org/u/PrzemekP)\
**Post date:** [June 10, 2020, 11:59am UTC](https://discourse.threejs.org/t/how-to-dynamically-adjust-the-camera-in-three-js/15593/3 "2020-06-10T11:59:26Z")

</div>

Thanks for the reply. Unfortunatly this has no effect on my code. box.getSize() returned NaN for one obj file and -Infinity for the big obj file.  
Any other suggestions?

---

<div class="post-metadata">

**Author:** ![Mugen87](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.threejs.org/mugen87/32/5645_2.png) [@Mugen87](https://discourse.threejs.org/u/Mugen87)\
**Post date:** [June 10, 2020, 12:12pm UTC](https://discourse.threejs.org/t/how-to-dynamically-adjust-the-camera-in-three-js/15593/4 "2020-06-10T12:12:46Z")

</div>

> [@PrzemekP](#):
>
> Unfortunatly this has no effect on my code. box.getSize() returned NaN for one obj file and -Infinity for the big obj file.  
> Any other suggestions?

Instead of trying something different it makes probably more sense to find out why these unusable values are returned in your case.
