Adjust camera to align with the loaded object in Three.js

I've been struggling to center the camera around the model loaded through the stl loader. I've tried adjusting variables and setting different positions for the mesh and camera, but the camera still isn't centered on the design!

Here's the code snippet I've been working with:

function init() {

            camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 );
            camera.position.set( 0,60 , 100 );

            controls = new THREE.OrbitControls( camera );
            controls.addEventListener( 'change', render );

            scene = new THREE.Scene();
            scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );

            // Loading the model
            var loader = new THREE.STLLoader();
            loader.addEventListener( 'load', function ( event ) {

                var geometry = event.content;
                var material = new THREE.MeshPhongMaterial( { ambient: 0xff5533, color: 0xff5533, specular: 0x111111, shininess: 200 } );
                var mesh = new THREE.Mesh( geometry, material );

                mesh.position.set( 0, 0, 0 );
                mesh.rotation.set( 0, 0, 0 );
                mesh.scale.set( 2,2,2 );

                mesh.castShadow = true;
                mesh.receiveShadow = true;
                camera.position.set( geometry.x,geometry.y , 100 );
                scene.add( mesh );

            } );
            loader.load('somefile.stl'); 

            // Setting up lights
            light = new THREE.DirectionalLight( 0xffffff );
            light.position.set( 1, 1, 1 );
            scene.add( light );

            light = new THREE.DirectionalLight( 0xffffff );
            light.position.set( -1, -1, -1 );
            scene.add( light );

            light = new THREE.AmbientLight( 0x222222 );
            scene.add( light );

            // Setting up renderer
            renderer = new THREE.WebGLRenderer( { antialias: false } );
            renderer.setClearColor( scene.fog.color, 1 );
            renderer.setSize( window.innerWidth, window.innerHeight );

            container = document.getElementById( 'container' );
            container.appendChild( renderer.domElement );

            // Event listener for window resize
            window.addEventListener( 'resize', onWindowResize, false );

        }

Answer №1

It appears there is some confusion between the camera's position and its target.

In order to focus the camera on the model, you can use camera.lookAt(mesh.position);. Make sure the camera is not placed inside the model, for example, use camera.position.set(0, 60, 100); for the original camera position, or geometry.x, geometry.y, 100 to view the model from the side, directly down the Z axis.

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

Encounter a snag when attempting to upgrade to React version 16.10.2 while working with Ant Design Components - the error message reads: "

After upgrading to the latest React version 16.10.2, I encountered issues while using Ant Design Components. I specifically wanted to utilize the Title component from Typography. Here is an example of what I was trying to do: import { Typography } from & ...

Is it possible to modify a variable within the readline function?

Can anyone help me figure out how to update the variable x within this function? const readline = require('readline'); const r1 = readline.createInterface({ input: process.stdin, terminal: false }); let x = 1; r1.on('line', fu ...

Unveiling the solution: Hide selected options in the input field of Material UI Autocomplete in React

I need help with not displaying the labels of selected options in the input field. I think it might be possible to do this using the renderInput property, but I'm not sure how. Even with the limitTags prop, the options still show up in the input field ...

Troubleshoot: Json causing issue with displaying markers on Google Maps API (v3)

I developed a custom Google Maps application using JSON data and implemented PostgreSQL database integration. Here is the code snippet: <script type="text/javascript"> var map; var national = [{"lng":"-6.173319","city":"JAKARTA","lat":"106.818 ...

Tips for customizing the timing of a Bootstrap modal's opening delay?

I have integrated gem "bootstrap-sass", "~> 2.3.0.0", which indicates that I am utilizing Bootstrap 2. Detailed information on the modal can be found here. The code for my custom modal looks like this: #Modal.modal.hide.fade{"aria-hidden" => "true" ...

Adding numbers to a textbox using a JavaScript algorithm

There are two textboxes in this scenario. The first box should always contain 4 digits when you leave it, while the second box should always contain 10 digits. A javascript function needs to be implemented so that when a user leaves one of the textboxes, ...

After clicking the create button in AngularJS, the ngModel values become empty

My form has been simplified by using ngRepeat to create the input fields. The attributes for each item are defined in my controller. Below is the code for the ModalCtrl: ... $scope.form = [ { label: 'First Name', fieldType: 't ...

Issue with external JavaScript file being unresponsive on mobile browser

Hello everyone, hope you're having a great afternoon or evening I've encountered an issue with mobile browsers like Chrome Mobile and Kiwi where the external js file is not visible in the html file. The script.js file looks like this: alert(&ap ...

Display various JavaScript function outputs in an HTML table for convenient tracking

Thanks to a helpful user on this platform, I was able to capture data from a JavaScript function and display it in an html table. However, I now have another query. How can I execute the function multiple times during page load and record the results in ...

Is there a way to make my DIVS update their content dynamically like buttons do, without manually adding an onclick function in the HTML code?

I am currently customizing a WordPress theme that lacks the option for onclick events on div elements. However, I can assign classes and IDs to them. In my design, I have four spans in a row, and when each span is clicked, I intend for the corresponding p ...

How can async/await help in retrieving the value of a CORS request?

Trying to make a CORS request and utilize async/await to extract the value from it (using jquery). The functions createCORSRequest and executeCORSRequest seem to be functioning correctly, so the implementation details are not my main concern. The function ...

Is it possible to utilize JSX independently of React for embedding HTML within a script?

Is it possible to incorporate inline HTML within a script using a library such as jsx? <script src="jsx-transform.js"></script> <script type="text/jsx"> define('component', function () { return (<div>test html code< ...

Javascript is not fetching the value

Here is the code snippet I am working with: var categoryDetailId = $("#createEventForm-categoryDetail-idCategory").val(); and this link from my rendered page: After clicking the button, it returns NaN Update: I tried setting it manually, but it still ...

Respond to the initial message within the "if" statement

client.on('message', message => { if (message.channel.type === 'text' && message.channel.name.toLowerCase() == "channel-2" && message.content === "test") { message.react("✅") } ...

Using Angular's $q service in the run block

I have a scenario where I need to load data from local files using the global loadJSON function (though it's not mandatory, it's recommended). Once the data is loaded from all the documents, I want to print the string 'i ve loaded'. T ...

What is the method for obtaining the current date when altering the system date to a previous time?

To ensure that my datepicker always displays the current date and does not allow selection of past dates, I need to update the date if the system date is in the past. If I change the system date to a past date, I don't want the datepicker to reflect t ...

Problem with UV mapping when adjusting texture size

I am currently working on an application to modify minecraft models. To display the drawn texture mapped on the 3D player model, I am using ThreeJS. However, I'm facing a challenge related to changing the texture size. Initially, the texture is mappe ...

Error: The createContext function is designed for use only in Client Components. To enable it, include the "use client" directive at the beginning of the file

After creating a fresh Next.js application with the app folder, I proceeded to integrate Materiel UI following the example provided in the documentation. However, I encountered an error: TypeError: createContext only works in Client Components. Add the & ...

Can you use an ajax post to search for a boolean in MongoDB without converting on the server side?

I am facing an issue with my mongo collection that has documents containing a boolean field: { name : "Tom", active : true } { name : "Jerry", active : false } In my application's client side, there is an element that triggers an AJAX po ...

Using Jest: A guide to utilizing a mocked class instance

When working on my frontend React application, I decided to use the auth0-js library for authentication purposes. This library provides the WebAuth class which I utilize in my code by creating an instance like so: import { WebAuth } from 'auth0-js&ap ...