What is the best way to ensure the three.js canvas is centered on the

I'm encountering a strange issue with my three.js canvas. I'd like it to be centered inside a div and not fill the entire page.

In the code snippet below, you'll notice that the canvas is nested within the div. Despite my efforts, including adding test headings for reference, the canvas appears to be shifting outside of the designated div, leaving me puzzled as to how to resolve this.

<head>
    <meta charset=utf-8>
    <title>My first three.js app</title>
    <style>
        body { margin: 0; }
        #test {
            width: 100px;
            height:100px;
            margin: 0px auto;
            border: 1px solid red;
        }
    </style>
    <style type="text/css" src="css/main.css"></style>
</head>
<body>
    <div id="test">
        <h1>test1</h1>
        <canvas id="canvasID"></canvas>
        <h2>test2</h2>
    </div>  
    <script src="https://github.com/mrdoob/three.js/blob/master/examples/js/Detector.js"></script>
    <script src="three.js-master/build/three.js"></script>
    <script>
        var scene = new THREE.Scene();
        var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
        var canvas = document.getElementById("canvasID");
        var renderer = new THREE.WebGLRenderer({ canvas: canvas });

        renderer.setSize( window.innerWidth*0.9, window.innerHeight*0.9 );
        document.body.appendChild( renderer.domElement );

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

        camera.position.z = 5;
        function render() {
            requestAnimationFrame( render );
            cube.rotation.x += 0.01;
            cube.rotation.y += 0.01;
            renderer.render( scene, camera );
        }
        render();

        if (Detector.webgl) {
            init();
            animate();
        } else {
            var warning = Detector.getWebGLErrorMessage();
            document.getElementById('container').appendChild(warning);
        }
    </script>
</body>

https://i.sstatic.net/1JklM.pnghttps://i.sstatic.net/2h78K.png

It's puzzling how the canvas seems to have "magically" shifted outside its parent div.

Answer №1

Your code includes the line

document.body.appendChild( renderer.domElement );
, which places the canvas at the end of the <body> tag. This means that the canvas is being added outside of the necessary div.

To resolve this, you can insert your canvas within the desired div using a simple JavaScript selector like:

document.getElementById('test').appendChild( renderer.domElement );

Alternatively, you could use:

document.querySelector('#test').appendChild( renderer.domElement );

This method ensures that the renderer is placed inside the div with id="test". Feel free to reach out if you encounter any issues with this solution.

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

Bring in 2 Angular applications into a different JavaScript project

In my current setup, I have 2 distinct Angular projects. To build each project, I execute the following CLI command: ng build --prod --output-hashing=none Following this command, the build process generates the below files for each project: runtime.js ...

Guide to directing a user through an Ajax call to a particular Controller and action

Here is a custom JavaScript function that updates data when the Update button is clicked. function UpdateData() { var obj = { "testData": $("#hdn_EditdsVal").val(), "feature": $("#hdn_EditdsVal").val() }; $.ajax({ url: ...

Seeking clarity on which specific section of this Node.js code is overseeing the routing of my POST request to the mongoose/mongodb server

Hey everyone, I'm diving into the world of programming and currently enrolled in a Udemy course on web development. As I progress through the lessons, there's one aspect of the code that's leaving me confused. I've got my MongoDB databa ...

The Node.js controller is in disarray

As a newcomer to javascript, node.js, and backend development in general, I am tackling the task of creating a controller for handling login page requests. My confusion lies in extracting data from a MYSQL table, user authentication, and working with the J ...

The JavaScript code successfully updates the text displayed on the button, but for some reason, the changes are not reflected when the button is clicked and the text received from the

In my current project, there is a textbox accompanied by a button labeled "Activate". Whenever the user modifies the text in the textbox, the button's label switches to "Search". In the backend code, it distinguishes between the button displaying "Sea ...

How can JavaScript nested AJAX requests and promises be properly chained together?

I'm currently facing a dilemma when it comes to setting the correct order of execution for the tasks at hand. Let's say I need to initiate an AJAX call, then handle the data and store it in IndexedDB using the idb-keyval library, which operates o ...

Is there a way to utilize Babel with Webpack while keeping the original folder structure of the source code intact?

I am currently working on a project that has a complex hierarchy as shown below: -src/ -app.js (interacts with server-side code only) -server/ -models/ -routes/ ... -client/ -views/ -scss/ - ...

Utilizing WebVR technology for measuring eye separation distance

I am currently working on developing a WebVR environment using Three.js. I have exported some scenes from Cinema4D and successfully loaded them into my project using the Colladaloader functionality provided by Three.js. As I wanted to test this environment ...

Is there a way to sort through objects in a JSON file using two shared values? Specifically, I'm looking to filter the JSON objects based on both common x and y values

Given a JSON file, I am looking to group objects based on common x and y values. Essentially, I want to group together objects that share the same x and y properties. Here is an example of the JSON data: let data = [{ "x": "0", "y& ...

Use CSS elements selectively on specific pages within Mkdocs

Currently, I am utilizing mkdocs in conjunction with the material theme to produce documentation. I am interested in incorporating section numbers on specific pages. To achieve this, I have implemented the following method for generating section numbers. ...

What could be the reason behind the failure of this :after element?

I am facing an issue with the preloader on my webpage where the animation is not displaying as expected. The animation should appear on top of a dark black background before the page fully loads, but it seems to be missing. The CSS for the animation works ...

Error message: Unable to suggest as Typeahead.js does not recognize the function

After struggling extensively with Twitters typeahead.js, I have finally reached the point where I need to choose a template for my suggestions. However, when attempting to do so, I encountered the following error: Uncaught TypeError: g.templates.sugges ...

Fetching JSON data from a Node.js server and displaying it in an Angular 6 application

Here is the code snippet from my app.js: app.get('/post', (req,res) =>{ let data = [{ userId: 10, id: 98, title: 'laboriosam dolor voluptates', body: 'doloremque ex facilis sit sint culpa{ userId: 10' ...

Determine the central point of the cluster with the most concentrated xy data points

In my project, I have a 200 x 200 square grid where users can vote on the next desired position of an object within this space. Each time a user submits their vote, the XY position is added to an array. Currently, to determine the "winning" position, I ca ...

Unable to insert controller into routeprovider

Currently, I am working on an exercise in AngularJS to enhance my skills focusing on routes. However, I am facing issues with getting the controller attributes to function correctly inside the routed template. Despite reading numerous tutorials, the code s ...

Why does Array Object sorting fail to handle large amounts of data in Javascript?

Encountered an issue today, not sure if it's a coding problem or a bug in Javascript. Attempting to sort an object array structured like this: const array = [{ text: 'one', count: 5 }, { text: 'two', count: 5 }, { text: 'thre ...

Can you explain how to convert a 32-bit floating point number from a Buffer to a JSON string in NodeJS while maintaining the original precision?

Given a buffer with single precision float numbers (32 bits, little endian), the goal is to create a JSON string holding those numbers while maintaining their original values without any loss of precision. The challenge lies in the fact that when a value ...

Mapping geographic coordinates with a null projection using D3

With d3.geo.path having a null projection due to TopoJSON already being projected, it can be displayed without any additional transformation. My goal is to plot data in the format of [longitude, latitude] on a map. Here is a simplified version of my code: ...

trigger an event from a different event in Node.js

I am attempting to retrieve the list of newly connected users in admin.html client.html (client login authentication) admin.html (notify new user join) server.js app.get('/', function(req, res){ res.sendfile('client.html'); }); ap ...

What is the process for adding a button and redirecting to a different view in MVC4?

I am facing an issue that I need help with. In my application, there is a view called CustomerMaster. This view includes fields such as 'Area', 'City', and more. If the city is already in the list, it automatically appears in a dropdow ...