When the button is clicked, I want the entire 3D object's width and height to adjust to fit on the left side of the screen, while displaying a div
HTML info on the right side.
How can I make the object fit on the left side of the screen? Can I use margin(px) for this purpose?
var camera, scene, renderer;
var geometry, material, mesh;
var lookDirection = new THREE.Vector3();
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
camera.position.z = 1;
scene = new THREE.Scene();
geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
material = new THREE.MeshNormalMaterial();
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.mouseButtons = {
LEFT: THREE.MOUSE.RIGHT,
MIDDLE: THREE.MOUSE.MIDDLE,
RIGHT: THREE.MOUSE.LEFT
}
controls.enableZoom = false;
}
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
controls.update();
TWEEN.update();
}
function fit(){
controls.enabled = false;
var box = new THREE.Box3().setFromObject(mesh);
var boxSize = box.getSize(new THREE.Vector3()).length();
var boxCenter = box.getCenter(new THREE.Vector3());
var halfSizeToFitOnScreen = boxSize * 0.5;
var halfFovY = THREE.Math.degToRad(camera.fov * 0.5);
var distance = halfSizeToFitOnScreen / Math.tan(halfFovY);
// compute a unit vector that points in the direction the camera is now
// in the xz plane from the center of the box
const direction = (new THREE.Vector3())
.subVectors(camera.position, boxCenter)
.multiply(new THREE.Vector3(1, 0, 1))
.normalize();
// tween animation
var from = camera.position;
var to = direction.multiplyScalar(distance).add(boxCenter);
var tween = new TWEEN.Tween(from)
.to(to, 1000)
.easing(TWEEN.Easing.Quadratic.InOut)
.onUpdate(function () {
camera.position.set(this.x, this.y, this.z);
// update the Trackball controls to handle the new size
controls.enabled = true;
controls.target.copy(boxCenter);
controls.update();
})
.start();
}
document.getElementById("btn").addEventListener("click", fit);
body {
margin: 0;
overflow: hidden;
}
button {
position: fixed;
top: 0;
left: 0;
}
<button id="btn">Fit</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/104/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script src="https://sole.github.io/tween.js/build/tween.min.js"></script>
Thanks!