Search code examples
javascripthtmlcssthree.jsrendering

Getting three.js scene to show up centered within a container


I am trying to have my three.js scene show up above some some cards & right underneath my nav-bar. Right now my scene is rendering underneath the cards, without being centered . After searching for other related forum posts, I can't seem to figure out what I am 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();

I greatly appreciate anyone's help! Let me know if more context is needed to provide an answer.

Edit: I switched document.body.appendChild( renderer.domElement ); To document.querySelector('#canvas').appendChild( renderer.domElement ); This change is now throwing a TypeError: null is not an object exception in the console & and nothing is being rendered.

Edit: I also tried document.getElementById('canvas').appendChild( renderer.domElement ); but this also results in the same exception being thrown in the console.

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


Solution

  • After using the document.getElementById("canvas") call, I put my script tag in the head of my HTML. I also added defer into my script tag in so that my script is executed after the page finishes parsing.