What is the best way to align a gltf model in the center of the viewport using threejs?

Recently diving into threejs, I've encountered an issue with moving both an imported gltf model and navigating the camera around said model. My objective is to position the model at the exact center of the canvas, but currently it appears to be cut off at the top. When I set camera.up.set(0,0,0), I achieve the desired result but at the cost of the orbit controls not functioning as intended.

Adjusting the camera.position.y only seems to cause rotation around a point, eventually leading to a top-down view of the model.

Here is the current display using the code below:

https://i.sstatic.net/BAUC8.png

This is the desired look without having to set camera.up.set(0, 0, 0) https://i.sstatic.net/Lpzgv.png

import React, { useEffect } from 'react';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import {useSelector} from 'react-redux'
import * as THREE from 'three';
const GarlicSan = () => {
  useEffect(() => {
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(
      45,
      266 / 400,
      45,
      4000
    );
    camera.position.set(
     0, 300, 1000
    )
    //camera.up.set( 0, 0, 0 );
    const canvas = document.getElementById('garlic'); 
    const renderer = new THREE.WebGLRenderer({canvas, antialias: true});
    const updateCanvas = () => {
      renderer.setSize( 266, 400);
      document.body.appendChild(renderer.domElement);
    };
    updateCanvas();
    // controls

    const controls = new OrbitControls(camera, renderer.domElement);
    controls.enableDamping = true;
    controls.enablePan = true;

    //model loader
    const loader = new GLTFLoader();
    loader.load('/chibi_garlic/scene.gltf', (gltf) => {
      scene.add(gltf.scene)
      renderer.render(scene, camera)
    });

    renderer.setClearColor( 0xffffff, 0);
    const animate = () => {
      controls.update();
      renderer.render(scene, camera);
      window.requestAnimationFrame(animate);
    };
    animate();
  }, []);

  const type = useSelector((state) => state.content)
  return(
    <>
    { type.content === 'lobby' ? (

      <canvas className=' absolute z-50 left-0 right-0 mx-auto top-[20%]' id='garlic'></canvas>
    ) : ( <canvas className=' absolute z-50 left-1 transition-all' id='garlic'></canvas>
 )}
    </>
  )
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Answer №1

If you are experiencing a similar problem, it may be due to the default target set to 0, 0, 0 when using orbit controls. As a result, when adjusting the camera position, it will revolve around that target in the x, y, and z axes. In my case, I had positioned my model directly on top of the 0, 0, 0 coordinates, so I resolved this issue by setting controls.target.set(0, 300, 0) after defining the controls.

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

Apply a chosen style to the element that was clicked on, while removing the style from the rest

Here is an example of my ul li structure: <div id="categoryTree"> <ul> <li id="cat_15"> <a class="hasSubCat" href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">N ...

Laravel is unable to interpret formData

I've been on a quest to find answers, but so far I'm coming up empty. I'm trying to send file input to a Laravel controller via Ajax, but it seems like the controller can't read the data at all. Here is my Ajax code: let fd = n ...

Watching for changes to an object's value in an AngularJS service triggered by a controller from a separate module (Extended Edition)

Referring to this discussion on Stack Overflow: AngularJS trigger and watch object value change in service from controller The original question was about watching for changes in a service from a controller. I am interested in extending this concept to ...

[.TextureUnitWarning] ALERT: Unit 1 is lacking a texture binding for rendering test.html:1

I've been attempting to incorporate texture into my project. var bumptexture = THREE.ImageUtils.loadTexture('grid.jpg'); var normaltexture = THREE.ImageUtils.loadTexture("normal.jpg"); var diffusetexture = THREE.ImageUtils.loadTexture ...

Images in Chrome are shivering when animated at unconventional positions

I am attempting to create a masking animation that reveals an image from its center. The animation is working well, but I have encountered a problem in Chrome where the revealed content shakes. Here is an example on jsfiddle: http://jsfiddle.net/BaKTN/ I ...

Turn off laptop camera to assess web application functionality in the absence of a camera on the device

In the process of creating an automated testing framework in Java and Selenium, I have encountered a scenario where I need to examine how a web application behaves when accessed by a user with a device lacking a camera. Is there a method to simulate this ...

Obtain JSON information and insert it into an HTML element

I'm currently faced with an issue regarding JSON data (fetching and posting it). Below is the code I have used, but unfortunately it is not working and I am unsure why. Upon checking with Firebug, it indicates the response as: 200 OK sourceforge.net 1 ...

The div element with the id "wrapper" is not functioning properly within the box model

I have defined an ID wrapper in CSS: #wrapper { position: relative; background: yellow; -webkit-box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.2); box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.2); width: 960px; padding: 40px 35px 35px ...

When running the test, the message "Unable to resolve all parameters for BackendService" is displayed

Upon executing the ng test command, the following error was displayed. This is my service specification: describe('BackendService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ { p ...

Default page featuring an AngularJS modal dialog displayed

I am attempting to display a modal popup dialog using an HTML template. However, instead of appearing as a popup dialog, the HTML code is being inserted into the default HTML page. I have included the controller used below. app.controller('sortFiles&a ...

The page is not responding after closing the modal dialog

My web application is built using Spring Boot for the backend and Thymeleaf for the front end. The app displays all available groups for users to review. When a user clicks on a group, the documents within that group are listed in a tabular form. Clicking ...

Loading custom places in ArcGIS from a file or database

Hey there, I was wondering about loading custom places with Arcgis similar to Google maps loading from a .xml file. I noticed that Arcgis uses examples saved in .json format, but when I tried putting the example .json on my local server it wouldn't lo ...

Issue with React Router version 6: displaying an empty page

I am currently grappling with implementing react-router for my react applications. However, I am encountering issues with the routing part as it consistently displays a blank page. Below are snippets of the code from the involved files: index.js import R ...

Adjust the window size smoothly to accommodate various height dimensions

Providing Some Background: I am currently developing a Chrome Extension where users have the option to launch it via the default "popup.html", or detach it from the top right corner to use in a separate popup window using window.open. This question also ...

What is the best way to retrieve specific JSON data from an array in JavaScript using jQuery, especially when the property is

Forgive me if this question seems basic, I am new to learning javascript. I am currently working on a school project that involves using the holiday API. When querying with just the country and year, the JSON data I receive looks like the example below. ...

Edit: "Submit a binary file with just JavaScript"

I am currently developing a Chrome application that utilizes the HTML5 Filesystem API to enable users to import and synchronize files. A challenge I'm facing is when attempting to sync image files, as they appear to become corrupted during the upload ...

What is the correct method for adding a button to a popup in Leaflet Draw?

I need a button within a popup that can perform an action on the attached layer. L.marker(coors[i], { icon }) .addTo(this.drawnItem) .bindPopup(this._getCustomIcon(mix)) .openPopup(); Here is my _getCustomIcon() function: ...

Ways in which the user can modify the city name within this inquiry

I am just beginning to learn JavaScript and I am struggling to figure out how to allow the user to change the city name in this request. Currently, it works when I manually input the city name in the code (e.g., askWeather.open("GET", "url.../london")), bu ...

Are you experiencing issues with modal contents extending beyond the modal on smaller screens?

I recently installed a modal plugin called blockUI for my image uploading needs. Although I have styled and positioned everything accordingly, I am facing an issue: Whenever I resize the browser screen, switch to my iPhone, or use another screen, some con ...

What is the best way to sequentially slide down multiple elements with a time delay in between each one?

I have multiple div elements with the same class. I have selected them all and I am iterating through each one to slide down every element. My goal is to first slide down the initial element, then introduce a delay before moving on to the next slide. Here ...