How can I position an object in Three.js to perfectly align with the left half of the screen, adjusting both its width

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!

Answer №1

Seems like you have an HTML/JavaScript query

An elegant solution would involve utilizing a flex box layout

function toggleDisplay(){
   const element = document.querySelector('#panes> .right');
   element.style.display = element.style.display === 'none' ? '' : 'none';
}

document.getElementById('btn').addEventListener('click', toggleDisplay);
html {
  box-sizing: border-box;
}
*, *:before, *:after {
  box-sizing: inherit;
}
body {
  margin: 0;
}

canvas {
  display: block;
  width: 100%;
  height: 100%;
}
#panes {
  display: flex;
  width: 100vw;
  height: 100vh;
}
#panes>.left,
#panes>.right {
  flex: 1 1 50%;
  height: 100%;
}

#panes>.left {
  padding: 1em;
  text-align: center;
  background: red;
}

#panes>.right {
  padding: 1em;
  background: blue;
  color: white;
}

button {
  position: fixed;
  top: 0;
  left: 0;
}
<div id="panes">
  <div class="left"> Stuff On Left</div>
  <div class="right" style="display: none;">Stuff on right</div>
</div>
<button id="btn">Toggle Display</button>

Consider adding the canvas to the left pane and refer to a more suitable example for adjusting canvas size dynamically

var camera, scene, renderer;
var geometry, material, mesh;

init();
animate();

// Rest of the JavaScript code...
CSS Styles...
HTML Code...

Answer №2

Thank you for your patience while I respond to this question. I believe I have found a solution that may be exactly what you are looking for. Please take a look at Is there ANY way to have the three.js camera lookat being rendered off-center?

camera = new THREE.PerspectiveCamera( for, aspect, near, far );

camera.setViewOffset( fullWidth, fullHeight, widthOffset, heightOffset, viewWidth, viewHeight );

You can use the widthOffset and heightOffset parameters to adjust the target of your camera to any side.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Making AJAX requests with Laravel using the XMLHttpRequest object is a

When using Laravel to upload a file and create a progress bar with ajax requests, the form action routes to the controller in this way: <form action="{{ URL::route('upload-file-form-post') }}" method="POST" enctype="multipart/form-data"> ...

Tips for transferring a variable from a hyperlink to a Flask application

Here is a snippet of my Python Flask code: @app.route('/ques/<string:idd>',methods=['GET', 'POST']) def ques(idd): print(id) And here is the accompanying Javascript code: var counts = {{ test|tojson }}; var text = ...

What are the benefits of using React.useMemo or React.useCallback within component props?

Exploring efficient ways to implement TailwindCSS in React, considering its utility-first nature leading to component-heavy code (e.g. className="w-full bg-red-500"). One approach is creating a utility function like: utils/tailwind.ts const tw = (...clas ...

What is the mechanism behind jQuery triggering the execution of JavaScript code contained in script tags that are retrieved in an AJAX response?

What is the unique ability of jQuery that allows JavaScript code inside script tags in an AJAX response to be executed? In the absence of jQuery AJAX, using eval() has been a common method to achieve this functionality as discussed in posts such as: Cal ...

Create a new instance of the TypeScript singleton for each unit test

I have a TypeScript singleton class structured like this: export default class MySingleton { private constructor({ prop1, prop2, ... }: MySingletonConfig) { this.prop1 = prop1 ?? 'defaultProp1'; this.prop2 = prop2; ...

Guide to Creating Maximum Intensity Projection [MIP] in WebGL

I have experimented with three.js in a demo [ http://jsfiddle.net/georgeneil/cfrsj/16/ ] where I utilized blending, specifically THREE.AdditiveBlending. However, this has resulted in a white light effect that seems to diminish the overall information conve ...

What could possibly prevent Jasmine Spyon from being named?

I am currently facing an issue with a failing test even though I have included the necessary calls. One specific area where I am encountering this problem is with the PrimeNG Message Service that I am spying on. Below, you can find the code snippet that I ...

emptyQueue in jQuery

I'm currently working with a jQuery script that takes the src of an image, places it in a hidden div, and enlarges the image with an animation when hovering over the requested image. However, I've encountered an issue where the clearQueue or stop ...

Navigational problem of Mapbox applied in THREE.js for 3D modeling

I am currently working on a unique custom layer for Mapbox that utilizes Three.js to render 3D objects. My main objective is to load these 3D objects onto the map and have them displayed at specific latitude and longitude coordinates. While I have managed ...

I am encountering an issue where my .glb file is not appearing in the dist/assets directory while working with react.js and three.js

I recently developed an app using react.js and Vitejs, where I integrated a 3D model using Theejs (.glb file). Surprisingly, when I run npm run dev, the 3D model works flawlessly without any issues. However, upon running npm run build, I noticed that the 3 ...

Error code 12004 encountered during the execution of a service request

While working on a service call in my JavaScript code that retrieves XML data using XMLHttpRequest, everything runs smoothly in Chrome and Firefox, successfully fetching the data over HTTPS. However, when attempting to execute the same code in IE11, it ret ...

Tips for extracting parameters from a JSON String using JavaScript

When attempting to parse a JSON String, I am encountering an issue where the parsed value is coming up as undefined. You can view the code on this jsfiddle link. <input type="submit" onclick=testJSON() value="Test"/> <div i ...

"Utilize the on() method to bind a click event to dynamically generated elements received

After reading several discussions on using on() to link events to dynamically generated HTML elements, I decided to create an example (FIDDLE) where the click event is bound to elements div.clicktitle fetched via AJAX. These div elements contain data attri ...

retrieve dynamically generated content following successful login using cURL

It's common knowledge that curl doesn't process JavaScript, it only fetches static HTML. This is why a simple curl command won't suffice for my needs. I'm not well-versed in PHP, still new to this field. From what I've gathered so ...

The Tab style in Mobile Angular UI does not get applied correctly when nested within an ng-repear

While working on a tabbed control with mobile-angular-ui (), I encountered an issue when trying to generate the tabs dynamically. Initially, everything looked good with the following code: <ul class="nav nav-tabs" ui-state='activeTab' ui-def ...

What are the steps for combining AngularJS with Java JAAS authentication system?

My web application combines AngularJS on the frontend with Java on the backend. Angular communicates with the Java backend through Restful webservices exchanging JSON data over HTTP. I am in need of developing an authentication mechanism for this app and I ...

Modification of window size using jQuery animations

Currently, I am working on creating a sidebar that slides in from the left side of the screen. To achieve this effect, I have set the menu element to float left with a width of 40% and a margin-left of -40%. However, when I try to reveal the sidebar by sw ...

Creating a customizable range input for pixel values: a step-by-step guide

I am looking to design a pixel range input. Here is an example: let slider = document.querySelector("input"); slider.addEventListener("change", () => { console.log(slider.value); }); <input type="range" min="5px" max="50px"> However, the r ...

How to enable real-time file changes detection in sails for development

I recently embarked on a new project using Sails (built on Express and Node.js). Currently, I am initiating my server with the command: sails lift However, whenever I make changes to the codebase, I need to manually restart the server. Is there a way to ...

What is the best way to transfer Flow type properties from one React component to another?

I'm in the process of developing a component that will wrap another component known as Button. The tricky part is that the library where Button is defined does not expose the type of its properties. In order to properly assign types to my component, ...