Import a 3-dimensional object from an .obj file and adjust its positioning within the camera view using Three.js

I am currently working on dynamically loading object files using THREE.OBJLoader and positioning them in the center of the scene or canvas to ensure the entire object is visible in the camera view. Since the objects are dynamic, I do not have fixed height or width data.

What I have achieved: https://i.sstatic.net/z2H3D.png

What I am aiming for: https://i.sstatic.net/o8E4h.png

References I have consulted so far:

  1. Three.js zoom to fit width of objects (ignoring height)
  2. How to Fit Camera to Object

  3. Smart Centering and Scaling after Model Import in three.js

  4. Adjusting camera for visible Three.js shape

  5. Calculate camera zoom required for object to fit in screen height

  6. Move camera to fit 3D scene

  7. Three.js calculate object distance required to fill screen

  8. How to calculate the z-distance of a camera to view an image at 100% of its original scale in a 3D space

Code Snippet:

camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000);

controls = new THREE.TrackballControls(camera);
controls.rotateSpeed = 5.0;
controls.zoomSpeed = 5;
controls.panSpeed = 2;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;

// scene
scene = new THREE.Scene();

var mtlLoader = new THREE.MTLLoader();
mtlLoader.setBaseUrl(path);
mtlLoader.setPath(path);
mtlLoader.setMaterialOptions({
    ignoreZeroRGBs: true
});

mtlLoader.load(path, function(materials) {
    materials.preload();
    var objLoader = new THREE.OBJLoader();
    objLoader.setMaterials(materials);
    objLoader.setPath(path);
    objLoader.load(path, function(object) {

        var helperBox = new THREE.BoundingBoxHelper(object, 0x888888);
        helperBox.update();
        scene.add(helperBox);

        //Scene
        scene.add(object);

        var boxFrmScene = new THREE.Box3().setFromObject(scene);
        var height = Math.max(boxFrmScene.size().y, boxFrmScene.size().x);
        var dist = height / (2 * Math.tan(camera.fov * Math.PI / 360));
        var pos = scene.position;
        var boundingSphere = boxFrmScene.getBoundingSphere();
        var center = boundingSphere.center;
        camera.position.set(center.x, center.y, (dist * 1.1));
        camera.lookAt(pos);
    }, function(error) {
        console.log(error);
    });
}, function(error) {
    console.log(error);
});

The object I used can be found here: . I am seeking guidance on the correct approach to solve this issue, especially since I am not well-versed in 3D mathematics. Any help would be greatly appreciated.

PS: Still struggling with 3D math concepts.

Edit: I have attempted the solution mentioned in this:How to Fit Camera to Object but it has not resolved my problem. In fact, it's flipping my object upside down. My goal is to position the object in the center of the camera.


Edit 2: I have made some progress on this issue. The object is now fully visible within the camera frustum. Next, I need to find a way to center it. I have updated the code snippet below scene.add(object);

var pos = scene.position;
camera.position.set(pos.x, pos.y, 100);
camera.lookAt(pos);
var boxFrmScene = new THREE.Box3().setFromObject(scene);
var height = Math.max(boxFrmScene.size().y, boxFrmScene.size().x);
var fov = camera.fov * (Math.PI / 180);
var distance = Math.abs(height / Math.sin(fov / 2));
camera.position.set(pos.x, pos.y, distance + (height / 2));
camera.updateProjectionMatrix();

Answer №1

After you've generated the mesh, consider incorporating the following code:

var box = new THREE.Box3().setFromObject(mesh);
box.center(mesh.position);
mesh.localToWorld(box);
mesh.position.multiplyScalar(-1);

Implementing this will accurately position your object at the screen's center.

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

Angular animation not firing on exit

I am encountering an issue with my tooltip component's animations. The ":enter" animation is working as expected, but the ":leave" animation never seems to trigger. For reference, here is a link to stackblitz: https://stackblitz.com/edit/building-too ...

Add a click function to an element in a grid when it is databound

In my TypeCtrl ES6 class angular controller, I am using a kendo datagrid directive with a template for grid config options. Within the grid template, I need to call a method from the TypeCtrl class when a span within the row is clicked. However, the functi ...

What is the reason that asynchronous function calls to setState are not grouped together?

While I grasp the fact that setState calls are batched within react event handlers for performance reasons, what confuses me is why they are not batched for setState calls in asynchronous callbacks. For example, consider the code snippet below being used ...

Creating a Delicious Earth Progress Pie

I'm looking to incorporate a unique progress bar design on my website, similar to this one: The progress pie Can anyone guide me on how to create a progress pie with an image inside it that changes color as it moves? ...

Electron triggers MouseLeave event on child elements

Dealing with mouse hover events can be a bit tricky, especially when working with AngularJS in an Electron-hosted app. Here's the HTML template and script I'm using: HTML: <div id="controlArea" (mouseenter) = "onControlAreaEnter()" ...

Updating a database seamlessly via a dropdown menu without having to refresh the entire webpage

Before we proceed, please take a look at the following code: $(document).ready(function() { $("#alternatecolor [type=button]").each(function() { $(this).on('click', function() { btnObj = $(this); rowId = $(this).attr("rowId") ...

The Discord.js collector seems to have no intention of ending, completely disregarding its keys in order

Help Needed with Discord Message Collector Issue I encountered a problem with my code that assigns ranks on Discord. It seems that the message collector is not responding to keys that should stop it from collecting messages. Can anyone offer assistance in ...

Leveraging the Power of jsPDF in Your Google Apps Scripts

Is it feasible to integrate jsPDF into a Google Apps Script project? I am attempting to create documents using templated HTML, but certain CSS styles like background-color do not translate to PDF when using the getAs() function. Given the limitations of ...

Access to PHP script (IF) unattainable following a POST occurrence

I'm completely new at this. I am attempting to create a contact form using HTML5 and PHP mail function, but I am facing an issue with my form action pointing to contacto.php. After submitting the form, it seems to be skipping over the IF condition wi ...

What is the difference between TypeScript's import/as and import/require syntax?

In my coding project involving TypeScript and Express/Node.js, I've come across different import syntax options. The TypeScript Handbook suggests using import express = require('express');, while the typescript.d.ts file shows import * as ex ...

Converting Javascript game information into PHP

Once the player loses, I need their score to be updated in the database using PHP. There is a separate JavaScript class that runs the game, utilizing setInterval to check the index.php function and update the database if the player loses. However, the issu ...

There was an issue with the specified entry-point "auth0/angular-jwt" as it is missing required dependencies

I am currently working on an Angular project with the following versions: @angular-devkit/architect 0.901.1 @angular-devkit/core 9.1.1 @angular-devkit/schematics 9.1.1 @schematics/angular 9.1.1 @schematics/update 0.901.1 rx ...

Determine the selected option in the dropdown menu upon loading the page and when clicked

I am working on capturing the value of a drop-down list whenever it is changed or when the page loads. The aim is to display different div elements based on the selected option in the report field - either State or Year. Any assistance with this would be ...

Using JQuery's $.ajax() method to send a post request and pass data to invoke a specific method in

I'm currently in the process of learning JQuery and encountering some challenges with utilizing the $.ajax() function. My goal is to send data to a controller for processing. During my debugging of the JQuery, it seems that the ajax call isn't b ...

Issue with window.location.href and unexpected behavior in Firefox 7

I can't seem to figure out the issue I'm encountering on FF7 My ajax calls are returning a json object (jquery). if(data.result=='ok') { var url = baseURL + "azioni/makeForm/" + data.actcode + "/DIA/" + data.az_id; console.log ...

Issues persist with debugger functionality in browser development tools following an upgrade from Angular 8 to version 15

After upgrading from Angular version 8 to version 15, I've encountered an issue where the debugger is not functioning in any browser's developer tools. Can anyone provide some insight on what could be causing this problem? Is it related to the so ...

Adjust the position of the footer up or down based on changes in page content height

If I have jQuery at my disposal, how can I achieve the following task? There is a div on the page with dynamic content and no fixed height. The height of this div changes as users type and content appears or disappears accordingly. Although everything is ...

Integrate the complete Mozilla pdf.js viewer into a Vue.js application using webpack through vue-cli

I am trying to integrate the full Mozilla pdf.js viewer into a Vue SPA. After reading a Stack Overflow post with an accepted solution, I still can't seem to get it to work. I keep encountering the 'Uncaught SyntaxError: Unexpected token <&apo ...

Looking to target an element using a cssSelector. What is the best way to achieve this?

Below are the CSS Selector codes I am using: driver.findElement(By.cssSelector("button[class='btn-link'][data-sugg-technik='append_numbers']")).click(); driver.findElement(By.cssSelector("button[class='btn-link'][data-sugg- ...

Can you please guide me on how to effectively configure a personalized time zone using MUI date picker combined with dayjs?

In my application, the user's time zone is supplied by the server instead of being determined by the browser's settings. When I receive a Unix timestamp from the server and pass it to the date picker, the displayed date is incorrect because the ...