How to display a three.js scene in the center of a container

I'm having trouble getting my three.js scene to display above some cards and right below my navigation bar. Currently, the scene is rendering under the cards and is not centered. Despite looking at other forum posts for help, I can't seem to figure out what I'm doing wrong.

HTML:

<script src="../static/javascript/three.js"></script>
<script src="../static/javascript/explore3D.js"></script>

<div class="container">
    <div class = "row">
        <div id="canvas"></div>
    </div>
</div>

<div class="py-5 bg-light">
    <div class="container">
        <div class="row">
            <div class="col-md-6">
                <div class="card mb-6 shadow-sm">
                    <div class="card-body">
                    </div>
                </div>
            </div>

            <div class="col-md-6">
                <div class="card mb-6 shadow-sm">
                    <div class="card-body">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS:

#canvas {
  position: fixed;
  outline: none;
}

JS:

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

const renderer = new THREE.WebGLRenderer();
renderer.setSize( 700, 400 );
document.querySelector('#canvas').appendChild( renderer.domElement );

const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );

camera.position.z = 5;

const animate = function () {
    requestAnimationFrame( animate );

    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;

    renderer.render( scene, camera );
};

animate();

Any help would be greatly appreciated! Let me know if more information is needed for a solution.

Edit: I changed

document.body.appendChild( renderer.domElement );
to
document.querySelector('#canvas').appendChild( renderer.domElement );
. Now, I am getting a TypeError: null is not an object in the console and nothing is being rendered.

Edit: I also attempted

document.getElementById('canvas').appendChild( renderer.domElement );
, but the same exception occurs in the console.

Edit: Referenced this post: Get Element By Id Not working. Is it possible that because I am calling this function before the page is rendered, the element I am looking for does not exist?

Answer №1

Once I utilized the

document.querySelector("#canvas")
method, I placed my script tag within the header section of the HTML document. Additionally, I included the defer attribute in my script tag to ensure that it runs after the page has been fully parsed.

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

What is the method for adjusting the right padding of the MUI Autocomplete Input field?

When using MUI, it automatically adds 65px of right padding to the outlined Autocomplete box. However, for my specific needs, I want to change this right padding to 50px. Despite my efforts to override the padding, I have been unsuccessful so far. You can ...

Angular 6 - detecting clicks outside of a menu

Currently, I am working on implementing a click event to close my aside menu. I have already created an example using jQuery, but I want to achieve the same result without using jQuery and without direct access to the 'menu' variable. Can someon ...

Create shorter nicknames for lengthy reference names within the ng-repeat loop

Is it possible to assign an alias to a long reference name in ng-repeat? Currently, I have 2 complex objects where one acts as a grouped index for the other. Although the ng-repeat template code is functioning correctly, it's getting hard to read and ...

Is there a way to customize the background color of the active list item class in Bootstrap 4?

Customizing Boostrap Code : <!-- Custom Sidebar --> <div class="bg-light border-right" id="sidebar-wrapper"> <div class="sidebar-heading"><strong><?= __('Admin Panel') ?></strong></div> <div class="li ...

Utilize JavaScript to iterate through a JSON object and retrieve the indices that meet the specified criteria

While I found a previous answer that somewhat addresses my issue, I am seeking guidance on how to return an array of the indexes where a specific value appears. For example, if **18A38** is the target value, it should return the positions [1,3]. The sampl ...

Using ASP.net MVC 4 to Implement Validation with Bootstrap Modal and PartialView

After switching from a simple View with validation to using a bootstrap modal and PartialView in my application, I encountered some issues. The client-side validation no longer works and the server-side validation redirects me to a new page instead of disp ...

Exploring Head-Linked/Off-center View in Three.js

I'm attempting to create a permanent head-coupled perspective without relying on the full headtrackr library. My head will remain stationary, but it will not be directly facing the screen. For those interested, I have a small demonstration available ...

Tips on preventing duplicate websocket clients in VueJS

Each time I access a component, it triggers the socket.on event. Additionally, there is a Vuejs button component as shown below. So when I emit to the 'socket.on('voice')' event in nodejs, the nodejs socket emits to the 'socket.on( ...

Retrieve the visible text content of an element by utilizing various ids

I am currently working on a project using AngularJS with multiple conditions all sharing the same id. My goal is to extract text only from the condition that evaluates to true. Recently, I discovered a major bug in an app that I am preparing for release. ...

Minimize the use of globalized variables in your LESS CSS code

Is there a better way to avoid using globally diffused variables? I conducted a test with the following setup: _import.less @test: #FFF; _import2.less @test: #000; test.less @import (reference) "_import"; body { background: @test; } test2.less ...

retrieve the coordinates of the northwest and southeast corners of a group of markers displayed on a Google Map

Is there a more efficient way to get the NE and SW corners of a set of markers on a Google map without iterating over each marker individually using JavaScript or Google functions? function fnSetBounds(){ var lowLat = 90; var highLat ...

What is the best way to incorporate multiple input boxes into a single alertbox for repeated use?

I attempted to use the same alertbox for 3 different input elements by converting it into a class and using getElementsByClassName, but unfortunately, it did not work as expected. Here is what I tried: <input type="text" class="form-control date notif" ...

Is it possible for me to alter the script for my button's onclick

Is there a way to replicate all properties of a div when creating a clone using JavaScript code? I have an existing script that successfully creates a clone of a div when a button is pressed, but it does not copy the CSS properties. How can I ensure that t ...

What is the best way to have a sound play when the page is loaded?

Is there a way to automatically play a sound when the page loads? <audio src="song.mp3"> Your browser does not support the audio element. </audio> I've attempted it with the following method: <script type="text/javasc ...

NodeJS CORS functionality failing to function properly in the Google Chrome browser

In my nodejs script, I have implemented CORS as shown below: var express = require('express') , cors = require('cors') , app = express(); app.use(cors()); To fetch JSON data from another domain, I am using an AJAX request. While ...

Making Angular table cells interactive with clicks

My table consists of multiple rows, and I want to change the color of a cell to red when clicked. However, only one cell should be red at a time. Whenever I click on a new cell, the previously red cell should return to its original color. How can I achieve ...

What is the process of embedding base64 encoded data into an image in Javascript after retrieving the data from Azure Blob Storage?

I am attempting to insert an image by utilizing the base64 data pattern, rather than a URL link. Initially, I retrieve the data from Azure Blob storage using the Azure Node.js SDK: Azure Node.js SDK After downloading the data as a string, I am unsure of ...

Can you suggest a method to save cookies or HTML5 localStorage across multiple WebBrowser instances on Windows Phone?

Quick question: How can I save data from Javascript in a WebBrowser control on my Windows Phone 8 app so that it remains even after the user closes and reopens the app? In more detail: I am working on a Windows Phone 8 app with a single WebBrowser contro ...

Leveraging Angular 6: Implementing custom scripts on a component basis and verifying their presence

I need some help with a script that I want to run on a specific component only. I've managed to add the script to the component, but there are a few issues that I'm unsure how to fix. When I go to the component, the script is added to the DOM b ...

Is it possible to change the background color using jQuery?

Can you assist me with this: I have a website and I am looking to modify the bg-coler when hovering over the menu (similar to how it works on the rhcp-website). I attempted using jquery for this, but unfortunately, it did not yield the desired result.. ( ...