Expand the size of the imported gltf model within Three.js

After successfully loading a 3d model with a gltf extension using the GLTFLoader in Three.js, I encountered a new challenge. I needed to adjust the dimensions of the model dynamically when the window is resized, based on the values of window.innerWidth and window.innerHeight.

const loader = new GLTFLoader();

// Loading the background box
loader.load('../../assets/backgroundBox.gltf', function(gltf) {
  scene.add(gltf.scene);
  gltf.animations;
  gltf.scene.rotation.z = Math.PI/2;
  gltf.scene.rotation.y = Math.PI/2;
  gltf.scene.castShadow = true;
  gltf.scenes;
  gltf.cameras;
  gltf.asset;
}, function(err) {
  console.log('An error occurred while loading files');
});

To address this issue, I attempted to add an event listener to the window object. However, I struggled to implement a solution that would change the dimensions of the loaded model in response to window resizing.

window.addEventListener('resize', () => {
  const width = window.innerWidth;
  const height = window.innerHeight;
  camera.aspect = width / height;
  camera.updateProjectionMatrix();
  renderer.setSize(width, height); 
});

Answer №1

Unable to figure out how to adjust the loaded model

The process of scaling objects remains the same in your case, with the only difference being that you need to consider resizing as well.

window.addEventListener('resize', () => {
    const width = window.innerWidth;
    const height = window.innerHeight;
    camera.aspect = width / height;
    camera.updateProjectionMatrix();
    renderer.setSize(width, height);
    
    if (loadedModel) {
        const scaleFactor = Math.min(width, height) / 600; //for example
        loadedModel.scale.set(scaleFactor, scaleFactor, scaleFactor);
    }
});

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

The 'type' property is not present in the 'ChartComponent' type, however, it is necessary in the 'ApexChart' type

Encountered an error highlighted in the title: Property 'type' is missing in type 'ChartComponent' but required in type 'ApexChart'. Any attempt to resolve this issue led to another error message: Type '{ type: string; ...

Retrieving attributes by their names using dots in HTML

Currently working on an Angular 2 website, I am faced with the challenge of displaying data from an object retrieved from the backend. The structure of the object is as follows: { version: 3.0.0, gauges:{ jvm.memory.total.used:{ value: 3546546 }}} The is ...

Retrieve the product IDs by selecting the checkboxes, then compile a fresh array consisting of the identified IDs

I am currently delving into the realm of typescript/angular2+ as a fledgling student, and I have taken on the task of creating a website to put my newfound knowledge to the test. The view is up and running, but I'm facing some roadblocks as I work on ...

What is the best way to set a fixed width for my HTML elements?

I am facing an issue with my user registration form where error messages are causing all elements to become wider when they fail validation. I need help in preventing this widening effect. How can I achieve that? The expansion seems to be triggered by the ...

Strategies for iterating over an array in React with TypeScript

I'm currently working on looping through an array to display its values. Here's the code I have: ineligiblePointsTableRows() { return this.state[PointsTableType.INELIGIBLE].contracts.map(contract => { return { applied: (&l ...

The @HostListener in Angular2 does not function correctly within a component that is inherited from another component

My Angular2-based client-side application has a base class: abstract class BaseClass { @HostListener('window:beforeunload') beforeUnloadHandler() { console.log('bla'); } } and two similar derived classes: @Component({ ...

Ensuring robust type safety when using various maps and multiple enums as their keys

I am working on creating a type-safe function for retrieving values from a map. The function needs to handle specific logic in my use case, which is why I require it beyond this simple example below: enum ExampleA { A = 'A' } enum ExampleB { ...

Choose datetime datepicker formatting in ng-pick

Currently, I am utilizing Angular and have incorporated the ng-pick-datetime npm. However, when attempting to adjust the format after selecting a date (dd/MM/yyyy), it consistently displays as (MM/dd/yyyy) instead. I am uncertain about how to rectify this ...

What is the best way to set a value for a variable that is asynchronous by design?

I'm currently working on an Appium automation framework that is typescript based. The element locator strategy used in this framework is async due to the nature of the plugin I am using, which requires the use of await. However, I encountered some err ...

Error in Mocha test: Import statement can only be used inside a module

I'm unsure if this issue is related to a TypeScript setting that needs adjustment or something else entirely. I have already reviewed the following resources, but they did not provide a solution for me: Mocha + TypeScript: Cannot use import statement ...

What causes the difference in inference for unspecified generics between a simple function call and a null-coalescing operator in TypeScript?

What causes the different types of a and b in the given code snippet? function empty<T>() { return [] as T[] } const defEmpty = empty() function test1(abc: number[]|null) { const a = abc ?? defEmpty const b = abc ?? empty() } Upon testing on t ...

Refreshing HTTP request in Angular

I am currently working with Angular 5 and have encountered the following issue: Within my route, I have a parameter called year. The component related to this route is supposed to display data based on the year parameter, which is fetched from a service. ...

What is the best approach for retrieving an image efficiently with Angular HttpClient?

My backend currently sends back an image in response. When I access this backend through a browser, the image is displayed without any issues. The response type being received is 'image/jpeg'. Now, I am exploring different methods to fetch this ...

How to successfully utilize TypeScript ES6 modules and RequireJS for registering Angular elements

I am in the process of updating a current Angular application that uses AMD with TypeScript 1.5 ES6 module syntax. Our modules are currently stored in separate files, and the main "app" module is defined like this... define('app', ['angular ...

Incorporating D3.js into Angular 6 for interactive click events

Currently working on building a visual representation of a tree/hierarchy data structure using d3.js v4 within an Angular environment. I've taken inspiration from this particular implementation https://bl.ocks.org/d3noob/43a860bc0024792f8803bba8ca0d5e ...

What's the best way to invoke this specific TypeScript function?

I have come across a library that includes the following function declaration: import { Auth0JwtStrategy } from './strategy/auth0-jwt.strategy'; import { Auth0Service } from './auth0.service'; import { Auth0Options } from './auth0. ...

Guide on updating a value in a Firestore document using Firebase

I am working on updating a specific portion of a document in my Firebase collections structure, specifically the phonebook(map) section. https://i.sstatic.net/UmHot.png When attempting to modify the document, I encountered an error saying Invalid documen ...

VSCode highlights issues that do not impact the compilation process

While working in VSCode, I notice numerous issues with TypeScript syntax, but oddly enough, these problems do not impact the compilation process. It's puzzling to me why my colleagues are unable to see these issues like I do. Is there a way for me to ...

"Exploring the magic of Vue.js and Three.js: A guide to seamlessly changing CSS style elements within an

I'm currently in the process of converting my Three.js project to Vue.js Within my Three.js scene, I have a 3D model with HTML points of interest attached to it. It is crucial that these points remain fixed to the model and consistently face the cam ...

How to resolve useState problem in useEffect when state is not null

Encountering issues with maintaining state in TypeScript React. A Child component passes a 'terminal' object to the Parent via a function called returnTerminal(). This 'terminal' object is then stored as a useState variable named _obje ...