Resizing a ThreeJs object based on the size of another object

I am currently utilizing threejs to display various models in gltf/glb format. These models vary in size, with some being large and others small. My goal is to standardize the size of all these models.

If I were to use mesh.scale(), it would only scale the object relative to its own size. Is there a method to achieve this without manually calculating the scale for each individual model?

UPDATE:

Below is the code snippet:

function loadModels(points) {
  // loader
  const loader = new GLTFLoader();

  const dl = new DRACOLoader();
  dl.setDecoderPath("/scripts/decoder/");
  loader.setDRACOLoader(dl);

  let lengthRatios;
  const meshes = [];

  for (let i = 0; i < store.length; i++) {
    loader.load(
      store[i].model,
      (gltf) => {
        const mesh = gltf.scene;
        const meshBounds = new THREE.Box3().setFromObject(mesh);

        // Calculate side lengths of model1
        const lengthMeshBounds = {
          x: Math.abs(meshBounds.max.x - meshBounds.min.x),
          y: Math.abs(meshBounds.max.y - meshBounds.min.y),
          z: Math.abs(meshBounds.max.z - meshBounds.min.z),
        };

        if (lengthRatios) {
          lengthRatios = [
            lengthRatios[0] / lengthMeshBounds.x,
            lengthRatios[1] / lengthMeshBounds.y,
            lengthRatios[2] / lengthMeshBounds.z,
          ];
        } else {
          lengthRatios = [
            lengthMeshBounds.x,
            lengthMeshBounds.y,
            lengthMeshBounds.z,
          ];
        }

        meshes.push(mesh);
        if (meshes.length == store.length) {
          addModels();
        }
      },
      (xhr) => {
        console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
      },
      (error) => {
        console.log("An error happened");
      }
    );
  }

  function addModels() {
    // Select smallest ratio in order to contain the models within the scene
    const minRation = Math.min(...lengthRatios);

    for (let i = 0; i < meshes.length; i++) {
      // Use smallest ratio to scale the model
      meshes[i].scale.set(minRation, minRation, minRation);

      // position the model/mesh
      meshes[i].position.set(...points[i]);

      // add it to the scene
      scene.add(meshes[i]);
    }
  }
}

Answer №1

It is recommended to outline a bounding box around each model for better visualization.

//Defining the bounding boxes
boundingBox1 = new THREE.Box3().setFromObject( object1 );
boundingBox2 = new THREE.Box3().setFromObject( object2 );

// Calculating dimensions of object1
let dimensionsObject1 = {
  x: Math.abs(boundingBox1.max.x - boundingBox1.min.x),
  y: Math.abs(boundingBox1.max.y - boundingBox1.min.y),
  z: Math.abs(boundingBox1.max.z - boundingBox1.min.z),
};

// Calculating dimensions of object2
let dimensionsObject2 = {
  x: Math.abs(boundingBox2.max.x - boundingBox2.min.x),
  y: Math.abs(boundingBox2.max.y - boundingBox2.min.y),
  z: Math.abs(boundingBox2.max.z - boundingBox2.min.z),
};

// Calculate dimension ratios
let dimensionRatios = [
  (dimensionsObject1.x / dimensionsObject2.x),
  (dimensionsObject1.y / dimensionsObject2.y),
  (dimensionsObject1.z / dimensionsObject2.z),
];

// Choosing the smallest ratio to fit both models in the scene
let minRatio = Math.min(...dimensionRatios);

// Applying the smallest ratio to scale the models
object.scale.set(minRatio, minRatio, minRatio);

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

Trouble with recognizing nested functions when calling them in an onClick event

Encountering a `not defined` error on the console when attempting to call nested functions with an `onClick` event in an HTML page. After searching for solutions without success, I suspect it may be a scope or closure issue, but I am unsure of how to addre ...

Managing the triggering of the automatic transition in view models

My question is straightforward and requires no elaborate explanation. Can Durandal be configured to control the use of transitions when transitioning between viewmodels? The motivation behind wanting to disable the animation is as follows: I have a sear ...

Identifying the Presence of a Marker in AR.js

Trying to figure out how to detect when a marker is found or lost in ar.js while using a-frame. After examining the source code, it appears that when the marker is found, a 'getMarker' event should be triggered, and artoolkit also dispatches a m ...

"Is there a way to transfer a value from one list box to another without needing to refresh the page, by utilizing AJAX,

Is there a way to automatically load Related Course levels in the Course Level Listbox when selecting a Course from the Course list? <script type="text/javascript" src="js/jquery.js"></script> <div>Course:<select name="course_id" id= ...

Like button for Facebook located at the bottom of a static webpage

I am facing an issue with my web application where it does not scroll properly, especially when there is a Facebook button at the bottom. The behavior in Chrome and Firefox is inconsistent and causing some trouble. In Chrome, the div repositions correctly ...

Assign values from an array in jQuery to a <span> element

I am working with the following HTML code: <input type='radio' class='at-radio' name='re_widget[0][set_style_for_widget]' value='topbanner' /> <span class='at-radio-label'>topbanner</span> ...

What is the method for assigning a link to a variable in JavaScript?

As I develop a website featuring an HTML course, I've opted for a consistent format for each lesson or page. One detail I've been working on involves setting a link within a button to a variable enclosed in quotes. For instance, I utilize the cod ...

Using RxJS to send a series of distinct AJAX requests on an event

Suppose I have an event type, such as a click event. I need to initiate 3 separate ajax requests through this event, but I want to listen for the final result of all 3 requests. What would be the most suitable design pattern for implementing this sequence ...

What is the best way to identify the clicked cell?

I'm a JavaScript newbie trying to work with ExtJS 3.4. I've set up a basic tree with 3 columns and now I want to figure out which cell, row, or column has been selected. Currently, I'm following the example provided by Sencha at : var tr ...

A method for cycling through parent and child objects in JavaScript (Vue.js) and storing them in an array - how to

I have a JSON object structured like this. const jsonData = { "id": "6", "name": "parent", "path": "/", "category": "folder", "fid": "6", "children": [ { ...

A guide on incorporating react-d3-components into a create-react-app project

I am interested in incorporating the charts from https://github.com/codesuki/react-d3-components into my react app that was developed using create-react-app. How can I seamlessly integrate the code? Here is an example of how to do it: var BarChart = Reac ...

Warning: The update depth in Nextjs has surpassed the maximum limit

I am currently developing a React Header component with a dropdown menu feature that can be toggled. Upon loading the page, I encountered the following error: next-dev.js?3515:20 Warning: Maximum update depth exceeded. This issue may arise when a compone ...

Can you explain the concept of "excluded" in relation to project subdirectories on Webstorm?

When using Webstorm, you have the option to mark project subdirectories as "excluded". However, the full implications of this designation remain unclear in the Webstorm documentation. Does marking a directory as excluded impact debugging or deployment proc ...

Retrieving JSON object Array from a Local Server through Firefox Results in CSP Error or NetworkError

Hey there, hope everyone is having a great night! I just got caught up in something for about an hour and a half, so I apologize in advance for taking up your time with this question. So, I'm trying to retrieve the posts from: http://localhost:5000/p ...

Comparing time in string format using a MongoDB aggregate query

My database has the following data stored: collection name: movies: [ {id:1, name:"abch", start:"12:00 pm", end:"03:00 pm"}, {id:2, name:"Annabelle", start:"08:30 am", end:"10:00 am"}, {id:3, name:"Spider Man homecoming", start:"11:30 am", end:"03:0 ...

Error: The carousel in Bootstrap is throwing a TypeError because f[0] is not

We are currently utilizing Bootstrap Carousel to load dynamic slides, with each slide corresponding to an item in an array. AngularJS is employed to create the array and iterate through it. However, during execution, we encountered a javascript error Type ...

Utilizing VueMq for personalized breakpoints and module inclusions

In my main app.js, I set and define breakpoints by importing the VueMq package. import VueMq from 'vue-mq'; Vue.use(VueMq, { breakpoints: { xsmall: 500, small: 768, medium: 1024, large: 1360, x ...

The date error from day.js in Firefox is not valid

My date is formatted as 2022-01-27 09:23:48 UTC and I am trying to parse it into MMMM-DD-YYYY format (Jan-27-2022) using day.js. The parsing works well in Chrome, but Firefox returns an 'Invalid' result. import dayjs from "dayjs" const ...

.submit fails to function when the bound object has been updated via an ajax call

I managed to implement an AJAX commenting system where, upon clicking the Post Comment button, an ajax call is made instead of submitting the form traditionally. Everything was working smoothly until I tried refreshing the page with the comment submit butt ...

Remove console.log and alert statements from minified files using uglifyjs-folder

Currently, I am minifying multiple files in a directory using the uglifyjs-folder feature within my npm configuration in the package.json file as shown below: "uglifyjs": "uglifyjs-folder js -eyo build/js" The process is effectively minifying all the fil ...