Tips on how to resize, position, and scale an object effectively using three.js

Recently delving into the world of three.js, I decided to experiment with importing models using the gltf loader. Upon loading a specific 3D model, my scene transformed to showcase a mesmerizing view, as depicted https://i.sstatic.net/l4jNy.png.

However, without the model in place, the background took on a whole new appearance after enabling alpha true and adjusting the canvas background to display a gradient, as seen https://i.sstatic.net/E3c7s.jpg.

The object I'm attempting to load appears like this https://i.sstatic.net/SHeEh.png.

I believe the discrepancy in the scene might be related to the camera angle or object scale. Below is the complete JavaScript code I am working with.

const loader = new GLTFLoader();
const gui = new dat.GUI()
loader.load('orange.glb', (gltf) => {
   browserscene.add(gltf.scene)
   gltf.scene.position.x = 10
   gltf.scene.position.y = 20
   gltf.scene.rotation.x = 0.2
   gltf.scene.rotation.z = 0.8
   gltf.scene.scale.x = 3
   gltf.scene.scale.y = 3

 });


  // Debug


  // Canvas
  const canvas = document.querySelector('canvas.webgl')

  // Scene
  const browserscene = new THREE.Scene()

  // Materials

   const material = new THREE.MeshBasicMaterial()
   material.color = new THREE.Color(0xFFFE00)

   // Lights

   var light = new THREE.HemisphereLight(0x404040, 0xFFFFFF, 10);
   browserscene.add(light);

   const sizes = {
     width: window.innerWidth,
     height: window.innerHeight
    }

     window.addEventListener('resize', () => {
      // Update sizes
      sizes.width = window.innerWidth
      sizes.height = window.innerHeight

       // Update camera
       camera.aspect = sizes.width / sizes.height
       camera.updateProjectionMatrix()

       // Update renderer
       renderer.setSize(sizes.width, sizes.height)
       renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
      })


      const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height, 0.1, 100)
      camera.position.x = 0
      camera.position.y = 0
      camera.position.z = 2
      browserscene.add(camera)


      const renderer = new THREE.WebGLRenderer({
         canvas: canvas, antialias: true, alpha: true
      })
      renderer.setSize(sizes.width, sizes.height)
      renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))

      const animate = () => {

      // Render
      requestAnimationFrame(animate)
      renderer.render(browserscene, camera)

    

     }

     animate()

Answer №1

It may be difficult to determine the appropriate size and position for the model without access to it. However, glTF models are typically designed to be in units of meters. Keep in mind that the model's adherence to this standard may vary depending on its source, such as if it was converted from a format that did not include units, like OBJ.

If you need to adjust the dimensions of the model, you can use the

THREE.Box3.setFromObject(gltf.scene)
method to calculate its dimensions. Keep in mind that this calculation is based on the assumption that your camera is positioned 2 meters from the origin.

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

Incorporate a jQuery userscript on Firefox that includes a link to a form

Attempting to incorporate a search link into an online form using a userscript with jQuery, specifically for Firefox. I typically work in Chrome, so I'm encountering some challenges with compatibility in Firefox. However, I need this to be functional ...

Finding a date from a calendar with a readonly property in Playwright

Just starting out with the playwright framework after working with Protractor before. I'm trying to figure out the correct method for selecting a date in Playwright. selector.selectDate(date) //having trouble with this ...

Using ng-repeat to iterate over an array of strings in Javascript

I am working with a JavaScript Array that contains strings: for(var i =0; i<db.length; i++) console.log(db[i]); When I run the code, the output is as follows: dbName:rf,dbStatus:true dbName:rt,dbStatus:false Now, I am trying to use ng-repeat to ...

Enhance jQuery dataTable with live updates from Firestore querySnapshot

Currently, I have implemented jQuery dataTable in my project to display data from Firestore. While everything seems to be working fine, an alert keeps popping up in the browser whenever there is an update in the Firestore data: DataTables warning: table i ...

Initiating an Ajax POST request by clicking a button

I have a button on my webpage that, when clicked, currently prints the value of an element to the console using a basic function. Instead of just printing the value, I want to update my Django view by sending it through a POST request. Here's the cu ...

Utilizing multiple instances of fs.writeFile in Node.js

I am currently managing a hotel's check-in/out information on an http server in Node.js. I store all the JSON data in memory and write it to a file using "fs.writeFile". Typically, the data does not exceed 145kB, but when consecutive calls to fs.write ...

What is the process for utilizing AngularJS's multiple $http calls to retrieve data from a single PHP file?

I'm currently experimenting with multiple AngularJS ajax calls to a single php file in order to retrieve different json data based on the request. Below is the code snippet I am working with: var myApp = angular.module('myApp', []); myApp ...

The scrollbar will be visible only when the mouse hovers over the table

I have been experimenting with customizing the scrollbar appearance of an ant design table. Currently, the scrollbar always displays as shown in this demo: https://i.stack.imgur.com/vlEPB.png However, I am trying to achieve a scroll behavior where the sc ...

When utilizing Vue JS, each key value of one computed property can trigger another computed property to run

I have a computed property: getRelatedItem () { return this.allItems.find((item) => { return item.id === this.currentSelectedItemId }) }, Here is an example of the output: relatedItem:Object -KQ1hiTWoqAU77hiKcBZ:true -KQ1tTqLrtUvGnBTsL-M:tr ...

Error: react-router v4 - browserHistory is not defined

I'm diving into the world of creating my very first React app within Electron (also my first experience with Electron). I have two routes that need to navigate from one to another. Here's the code snippet I am using: Root ReactDOM.render( < ...

Is it possible to pass a random variable into an included template in Jade?

In my jade template called 'main page', I have a reusable template named 'product template'. The 'product template' is designed to display dynamic data and needs to be flexible enough to be used in multiple pages without being ...

What is the best way to include the toast component in my button?

I am brand new to working with Next.js and React. I have a button in my project that triggers an external JavaScript file (query.js). After the script finishes executing, I would like to display a toast notification indicating whether it was successful or ...

Is it possible for me to create an If statement that can verify the current index within a Map?

I have the following TypeScript code snippet: export default class SingleNews extends React.Component<INews, {}> { public render(): React.ReactElement<INews> { return ( <> {this.props.featured ...

Guide to retrieving a specific cookie value with socket.io

I have successfully retrieved all cookies using the socket.request.headers.cookie. Upon console logging, the output appears as follows: PHPSESSID=mtklg8k81cpkop5ug6aechbb34; user=77; io=1Klg6xgTRXhb2OWiAAAA Now, I am trying to extract only the value of ...

Componentizing Vue for Better Reusability

Currently tackling a large application filled with legacy code, I'm facing a repetitive issue that has popped up twice already. It's becoming clear to me that there must be a more efficient way to solve this problem. Here's what I'm dea ...

Finding the appropriate method to access a template variable reference in a designated row of an Angular Material table (Angular 7)

Currently, I am working on implementing a more intricate version of a behavior inspired by Angular Material's tutorials. In my simplified example, an Angular Material table is populated with data from a string array. The first column contains input fi ...

Exploring Specific Locations with AmCharts 5 Zoom Feature

Just starting to use AmCharts 5 and I'm struggling to trigger a simple zoom into a location on a map. No matter which tutorial I follow, I can't seem to replicate the results others are getting. If you want to take a look at my Codepen setup to ...

Utilizing ajax for fetching a data table

I am new to using ajax and have successfully retrieved data from a table. However, I am now trying to pull in an entire data grid but not sure how to achieve this. In my index.php file, I have the following code: <html> <head><title>Aj ...

How to implement a Typescript interface without necessarily implementing the parent interfaces

Within my current project, I have defined the following interfaces: interface foo { fooProperty: number; fooFunction(): void; } interface bar extends foo { barProperty: string; barFunction(): void; } Now, I am interested in creating a class like ...

Enhancing performance by dynamically updating DOM elements when they come into view during scrolling

Currently, I am in search of an efficient algorithm to dynamically load background-images for a group of <li>'s but I am encountering some efficiency issues. The code I am using at the moment is as follows: function elementInView($elem, vps, vp ...