Is there a way to align a threejs object in the middle of a div container

My attempt at centering an object inside a div on my website using JS code has hit a roadblock. Despite trying various posted solutions, I haven't been successful. Any assistance would be greatly appreciated.

import * as THREE from 'three';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls.js';
import {GLTFLoader} from 'three/examples/jsm/loaders/GLTFLoader.js';
import {RGBELoader} from 'three/examples/jsm/loaders/RGBELoader.js';

// Scene 1 - Landing Page 

container = document.getElementById('canvas');
document.body.appendChild( container );


const renderer = new THREE.WebGLRenderer({antialias: true, alpha: true});

container.appendChild( renderer.domElement );

const div = document.getElementById('container');
div.appendChild(renderer.domElement);

renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( div.clientWidth, div.clientHeight,false);

const scene = new THREE.Scene();

const clock = new THREE.Clock();

const camera = new THREE.PerspectiveCamera(
    50,
    div.clientWidth / div.clientHeight,
    0.1,
    1000
);


const orbit = new OrbitControls(camera, renderer.domElement);

camera.position.x = 0
camera.position.y = 2
camera.position.z = 6
orbit.enabled = false
orbit.minDistance = 7;
orbit.maxDistance = 7;
orbit.update();

const gltfLoader = new GLTFLoader();

const rgbeLoader = new RGBELoader();

renderer.linearEncoding = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 10;

let obj1;
rgbeLoader.load('./assets/MR_INT-005_WhiteNeons_NAD.hdr', function(texture) {
    texture.mapping = THREE.EquirectangularReflectionMapping;
    scene.environment = texture;
    scene.background = null;


    gltfLoader.load( './assets/scene.gltf', function ( gltf ) {

        model = gltf.scene;
        scene.add(model);

        var textureLoader = new THREE.TextureLoader();
        textureLoader.load( "./textures/material0_baseColor.png", function ( map ) {
        model.material.map = map;
        model.material.map.encoding = THREE.sRGBEncoding;
        model.material.map.flipY = false;
        model.material.needsUpdate = true;
        });
    
        mixer = new THREE.AnimationMixer( model );
        
        gltf.animations.forEach( ( clip ) => {
          
            mixer.clipAction( clip ).play();
            obj1 = model;
        } );
    });

function animate(time) {
    requestAnimationFrame( animate );
    if (mixer) 
        delta = clock.getDelta();
        mixer.update(delta);
    renderer.render(scene, camera);
}

renderer.setAnimationLoop(animate);

window.addEventListener('resize', function() {
    camera.aspect = div.clientWidth / div.clientHeight;
    camera.updateProjectionMatrix();
    renderer.setSize( div.clientWidth, div.clientHeight,false);
});


});

This is the HTML structure.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./style.css"> 
</head>
<body>
    <div id="container">
        <div id="canvas"></div>
    </div>
    <div id="container2">
        <h1>
            <span class="box"></span><span class="text"></span><span class="cursor">_</span>
        </h1>
    </div>

    <script src="./js/scripts.js" type="module"></script>
    <script src="./js/app.js" type="module"></script>
    <!--
        npm install @parcel/config-default -d
        
        "staticFiles": {
    "staticOutPath": "static"
    }
    -->
</body>
<script src="./js/scripts.js" type="module"></script>
<script src="./js/app.js" type="module"></script>
</html>

And the CSS styling.

@import url('https://fonts.cdnfonts.com/css/modern-typewriter');
html {
  background-color: black;
  scroll-behavior: smooth;
  }
  
body {
    margin: 0;
    padding: 0;
    overflow-x: hidden;
  }

#container{
  background-color: blue;
  float: right;
  width: 500;
  height: 500;
}

h1 {
  position: relative;
  font-size: 2vw;
  font-weight: bold;
  padding-top: 20vw;
  padding-left: 5vw;
  overflow: hidden;
  color: aliceblue;
}

h1 .text {
  font-family: 'MODERN TYPEWRITER', sans-serif;
  font-weight: normal;
}

#container2{
  float: left;
  width: 50%;
}

The desired outcome can be seen https://i.sstatic.net/yc6JL.png.

Despite adjusting the camera positions and CSS script, the issue persists.

Answer №1

If you want an easy way to achieve this layout, simply nest them inside a container div.

#leftbox {
        float: left;
        background: Red;
        width: 25%;
        height: 280px;
    }

    #middlebox {
        float: left;
        background: Green;
        width: 50%;
        height: 280px;
    }

    #rightbox {
        float: right;
        background: blue;
        width: 25%;
        height: 280px;
    }

Reference: geekforgeeks

Answer №2

Give this a try. Remember to pay attention not just to the position of the divs but also how they are positioned on the canvas. Imagine it like a box within a box inside the biggest box.

body, html {
            margin: 0;
            padding: 0;
            height: 100%;
            overflow: hidden;
        }

        #container {
            display: flex;
            height: 100%;
        }

        #left {
            flex: 75%;
            background-color: black;
        }

        #right {
            flex: 35%;
            background-color: blue;
            position: relative;
        }

        canvas {
            width: 100%;
            height: 100%;
        }
<script type="importmap">
  {
    "imports": {
      "three": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="becad6ccdbdbfe8e908f8b87908e">[email protected]</a>/build/three.module.js",
      "three/addons/": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="04706c76616144342a35313d2a34">[email protected]</a>/examples/jsm/"
    }
  }
</script>

<div id="container">
        <div id="left"></div>
        <div id="right"></div>
</div>


<script type="module">
import * as THREE from "three";
import GUI from 'https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd919491d09a8894bdcdd3ccc4d3cc">[email protected]</a>/+esm';

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth * 0.3 / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setClearColor(0x000000, 0);
renderer.setSize(window.innerWidth * 0.3, window.innerHeight);
document.getElementById('right').appendChild(renderer.domElement);
camera.position.z = 5;

const geometry = new THREE.CylinderGeometry(0.5, 0.5, 1, 32);
const material = new THREE.MeshBasicMaterial({
    color: 0xff00ff,
    wireframe: true
});
const cylinder = new THREE.Mesh(geometry, material);
scene.add(cylinder);

const gui = new GUI()
gui.add(cylinder.position, 'x', -5, 5).name('Position X');

function onWindowResize() {
camera.aspect = window.innerWidth * 0.3 / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth * 0.3, window.innerHeight);
}

window.addEventListener('resize', onWindowResize);
function animate() {
requestAnimationFrame(animate);
cylinder.rotation.y += 0.001;
renderer.render(scene, camera);
}
animate();
</script>

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

Utilize a single function to toggle the visibility of passwords for multiple fields upon clicking

Is there a way to optimize the function used to hide passwords for multiple fields when clicked? Instead of having separate functions for each field, I would like to have one function that is only active on the clicked button. For example, if the toggle ...

Troubleshooting ASP.NET Ajax Error Code 0

Starting from scratch with asp.net and hoping to incorporate infinite scrolling using jQuery Ajax and ASP.NET MVC. Here's the progress so far: <div id="container"></div> <div id="progress" style="display:none"> <h4>Loading ...

Does Three.js perform automatic clipping?

Recently, I came across an interesting article on clipping in computer graphics on Wikipedia. It appears to be a crucial aspect in game development. I'm curious to know if I need to manually implement clipping, or if Three.js or WebGL handle it automa ...

Dynamic class/interface in Typescript (using Angular)

Is there a way to achieve intellisense for an object created with a dynamic class by passing parameters? Here is the code snippet: Main: let ita: any = new DynamicClass('ITA'); let deu: any = new DynamicClass('DEU'); The DynamicClass ...

What is the best way to encapsulate a function that uses `this.item.findElement()` from Selenium in a separate file?

I'm currently working on setting up a Selenium Webdriver and Cucumber.js test environment using Node.js. In the homePageSteps.js file, I have a check to verify if a banner exists on a page: Then('there should be a banner', async function() ...

Why do I have trouble choosing my radio buttons?

How come my radio buttons aren't responding when clicked on? I have to press next to the button to get it to select. What could be causing this issue? <!DOCTYPE html> <html> ... </html> ...

Issues arise with the blinking of my table rows

I'm working on a page with a table where certain rows need to blink under specific conditions. This page is a partial view that I load using the setInterval function. However, I've encountered an issue where the blinking functionality goes hayw ...

Prevent Bootstrap dropdown menu from closing when clicked on

Is there a way to keep the dropdown menu class in Bootstrap open after clicking a link inside it? I need users to be able to choose a class from "type-of-visitors" and select an option in the dropdown menu without it closing. The "Go" button should be th ...

Exporting strings to a text file with line breaks using AngularJS is a simple and effective process

When importing a text file like this https://i.sstatic.net/uixNp.jpg, the date will be formatted as shown here: https://i.sstatic.net/p90lC.jpg. After formatting, an automatically exports a notepad containing the new formatted date. However, the issue is ...

CSS - Ensure the parent stays open and the submenu remains highlighted upon selection

I have integrated a CSS Vertical menu with submenus into an ASP.Net application on the master page. Clicking on each menu item directs to different aspx pages. However, when clicking on a submenu within an expanded parent menu, the page redirects as expect ...

What is the process for linking dynamic content to document-ready events?

When it comes to jQuery and JavaScript, I admittedly struggle a bit. I have a specific question but can't seem to find the right search terms to get me there. It involves using either .trigger() or on(), but I'm unsure of the correct implementati ...

I'm trying to figure out how to incorporate this code into an arrow function while also utilizing the iterating array element

I am aiming to create a function that can provide either true or false based on whether the searchElement exists in the array. While I could achieve this with a simple for loop and if-else statement, my goal is to utilize an arrow function. Although JavaS ...

Layers of CSS images

Is there a way to create multiple layers for images on a webpage so they can move independently without affecting other elements? I attempted to use z-index, which did work, but it caused the page to increase in height. Additionally, when using jQuery.posi ...

Having trouble installing memlab using the npm package

Recently, I made an attempt to install the memlab library from Meta's GitHub. Initially, when I installed it without using the -g flag, the installation was successful. However, I encountered an issue where I could not execute any of the memlab comman ...

Using mySQLi to store query results in an array and display them in separate DIV containers

I am looking to efficiently query the content of multiple IDs (from 1 to 6) from a mySQL database using mySQLi. Once I retrieve the content, I want to display it in separate DIVs. Currently, I am using the following code which works perfectly: <?php $c ...

Display and conceal individual divs using jQuery

Despite my lack of experience with jQuery, I am struggling with even the simplest tasks. The goal is to display/hide specific messages when certain icons are clicked. Here is the HTML code: <div class="container"> <div class="r ...

Arrange your HTML pages using the Bootstrap 4 Navigation Bar

Inquiry: What is the standard or best practice for organizing multiple HTML sites or files with a navigation bar that should be visible on all pages? Background: As a beginner in website creation, I am working on a project to run on an ESP using Bootstrap ...

Objects That Are Interconnected in Typescript

I have been delving into TS and Angular. I initially attempted to update my parent component array with an EventEmitter call. However, I later realized that this was unnecessary because my parent array is linked to my component variables (or so I believe, ...

Link Array with Google Charts

I've been struggling for a long time to connect this array to a Google chart with no success. I would really appreciate some assistance in identifying what mistake I've made. I have created a jsfiddle where the array appears to be correct, and wh ...

Can you please point out the location of the error in the Java Script code

Our application is developed using Yii2 framework and incorporates Kartik's star-rating widget. However, there seems to be an error in the JavaScript code: Error message from console: Check out the problematic code snippet: <?php $js = ...