Implementing objects in a three.js scene without displaying them on the screen

I have a function called createCylinder(n, len, rad) that is being invoked from another function named createScene(). Despite checking that the vertices and faces are correctly added without errors, the geometry itself is not rendering. I suspect this issue may be related to the timing of returning the geometry or mesh and adding it to the scene. After trying various approaches unsuccessfully, I am seeking assistance in resolving this matter. Any guidance provided would be greatly appreciated. Thank you in advance!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cylinder</title>
</head>

<script type="text/javascript" src="three.js"></script>
<script type="text/javascript" src="OrbitControls.js"></script>

<style>
    body {
        /* set margin to 0 and overflow to hidden, to go fullscreen */
        margin: 0;
        overflow: hidden;
    }
</style>


<body>

<div id="container">
</div>
<div id="msg">
</div>

<script type="text/javascript">


    var camera, scene, renderer;
    var cameraControls;
    var clock = new THREE.Clock();
    var isCappedBottom = false;
    var isCappedTop = false;


    function createCylinder(n, len, rad) {

        var geometry = new THREE.Geometry();
        var radius = rad;
        var length = len;
        var yUp = length / 2;
        var yDown = -length / 2;
        var theta = (2.0 * Math.PI) / n;


        for (var i = 0; i < n ; i++) { //runs n + 2 times if we allow redundant vertices
            var x = radius * Math.cos(i * theta);
            var z = radius * Math.sin(i * theta);

            //Top to bottom
            var originUp = new THREE.Vector3(x, yUp, z);
            var originDown = new THREE.Vector3(x, yDown, z);
            geometry.vertices.push(originUp); //0 
            geometry.vertices.push(originDown); //1 

            console.log("Vertices " + geometry.vertices.length);

        }//end of first for loop

        for (var j = 0; j < 2*n; j+= 2) {
            var face1 = new THREE.Face3(j, j + 1, j + 2);
            var face2 = new THREE.Face3(j + 1, j + 3, j + 2);
            geometry.faces.push(face1);
            geometry.faces.push(face2);
            console.log("faces " + geometry.faces.length);
        }

       var material = new THREE.MeshLambertMaterial({color: 0xFF0000, side: THREE.DoubleSide});
        var mesh = new THREE.Mesh(geometry, material);
        return mesh;
        //scene.add(mesh);


        
     } 


    function createScene() {
        var cyl = createCylinder(10, 10, 2);
        return cyl;
       
    }


    function animate() {
        window.requestAnimationFrame(animate);
        render();
    }


    function render() {
        var delta = clock.getDelta();
        cameraControls.update(delta);
        renderer.render(scene, camera);
    }


    function init() {
        var canvasWidth = window.innerWidth;
        var canvasHeight = window.innerHeight;
        var canvasRatio = canvasWidth / canvasHeight;

        scene = new THREE.Scene();

        renderer = new THREE.WebGLRenderer({antialias: true, preserveDrawingBuffer: true});
        renderer.gammaInput = true;
        renderer.gammaOutput = true;
        renderer.setSize(canvasWidth, canvasHeight);
        renderer.setClearColor(0x000000, 1.0);
        renderer.shadowMapEnabled = true;

        camera = new THREE.PerspectiveCamera(40, canvasRatio, 1, 1000);
       
        camera.position.set(0, 0, 12);
        camera.lookAt(new THREE.Vector3(0, 0, 0));

        cameraControls = new THREE.OrbitControls(camera, renderer.domElement);
    }


    function addToDOM() {
        var container = document.getElementById('container');
        var canvas = container.getElementsByTagName('canvas');
        if (canvas.length > 0) {
            container.removeChild(canvas[0]);
        }
        container.appendChild(renderer.domElement);
    }

    init();
    createScene();
    addToDOM();
    render();
    animate();

</script>
</body>
</html>

Answer №1

When using the createCylinder function:

var mesh = new THREE.Mesh(geometry, material);
return mesh; // It is important to note that this line should always be the last line in the function
             // After the return(), any additional code will not be reached
//scene.add(mesh); // This line can be removed as the mesh is added in the createScene() function

The revised version of the createScene function would look like this:

function createScene() {
    var cyl = createCylinder(10, 10, 2);
    //return cyl;
    scene.add(cyl);
}

For a complete example, you can refer to this jsfiddle.

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

Conceal two DIV elements if one of them is empty

My slideshow has thumbnails connected to each slide. There are 10 DIVs representing the slides like this... <div class="SSSlide clip_frame grpelem slide" id="u751"><!-- image --> <?php while ($row = mysql_fetch_array($query ...

Implementing a way to send nested objects back in response to a jQuery get request

Using jquery.get() to request data from the Spring-Boot backend: var url = "http://localhost:8080/api/v1/get_holdings?userId=1"; $.get(url, function(payload,status) { if (status == "success") { $.each ...

Encountering a pair of errors while working with Node.js and Express

(Apologies for the vague title) I have been developing a project using Firebase and Express, but I am encountering some issues. src/index.js import { initializeApp } from "firebase/app"; import { doc, getFirestore } from "firebase/firesto ...

I'm attempting to integrate the map function into my React Redux application, but after implementing useDispatch, I'm encountering an error message in the console

I am currently troubleshooting an app I'm working on, but I keep encountering errors in the console. Included below is a picture of the error as well as the code snippet triggering the issue. Can anyone provide insight into what might be causing this ...

the div background is limited to the exact size of the text, not filling the entire

Currently, as I work on my web page using react.js, I'm facing the challenge of implementing a full-size background. Despite my efforts, the background only occupies the size of the text within the div. Here is the snippet of code I am working with: a ...

Enhancing the style of child elements in jQuery using CSS

My goal is to create a popup that appears upon mouse hover using jQuery and CSS. The code functions properly, but I'm encountering difficulty adding CSS to the child elements within the popup window. Below is the jQuery code: $(document).ready(fun ...

Navigating to lower levels of JSON data in JavaScript instead of starting with the top level

Using a microservice, I fetch multiple sets of JSON data and display them on a Vue.js-powered page. The structure of the data is as follows: {"data":{"getcompanies": [ {"id":6,"name":"Arena","addr ...

Messages traced by log4javascript are not being displayed

I am currently utilizing log4javascript version 1.4.3. Everything in my application seems to be functioning correctly with all log levels except for trace. To simplify the troubleshooting process and ensure that the issue does not lie within my applicati ...

Preserving the top line or heading while cutting through a table

In my HTML, I have a table with the following structure: <table id="table"> <tr> <td>ID</td> <td>Place</td> <td>Population</td> </t ...

What is the best place to define data that remains constant?

In a Vue component, I am looking to utilize data that remains constant. The issue arises when attempting to implement the following code: const numbers = [1, 2, 3] new Vue({ el: "#app" }) <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2 ...

Node.js refusing to acknowledge the get request handler for the homepage of the website

My Node.js server setup is quite simple: const express = require('express'); const app = express(); const http = require("http"); const path = require('path'); const favicon = require('serve-favicon'); // Public fil ...

jqGrid display/hide columns options dialogue box

I am looking to implement a feature that allows users to toggle columns in my jqGrid. I came across a module for this purpose, but unfortunately, it is no longer supported in jqGrid 4.x. I have searched for a replacement module without success. Are there ...

The ngAfterContentInit lifecycle hook is not triggered when the parent component updates the child component

I am trying to understand the functionality of the ngOnChanges callback in Angular. I have implemented it to observe changes in a property annotated with the Input decorator as shown below: @Input() postsToAddToList: Post[] = []; However, after compiling ...

Date Boxes in a Tangled Web

Looking to showcase multiple dates on a screen, I'm encountering an issue where clicking on a date button opens a datepicker. If the user clicks out of the box, the datepicker closes properly. However, when another datepicker button is clicked, instea ...

Save the currently active index of the mySwiper element even after the page is

After clicking through the carousel, I want to be able to store the current index and slide back to it after a page refresh. Is there a way to save this value in a variable so that I can use the mySwiper.slideTo() method to return to the last index? In si ...

Press anywhere on the screen to conceal the AngularJS element

Attempting to create a toggle effect using 2 ng-click functions. One is bound to a button, the other to the body tag. The goal is for my content to show when the button is clicked and hide when anywhere on the body is clicked. However, it seems that Angul ...

Can you explain the process of a put request in Angular, Express, and Mongoose?

My colleague and I are currently deciphering the inner workings of a code snippet generated by a tutorial. Our main focus is on how the client/server communication flows once line 8 of factory.js is triggered: factory.js app.factory('postFactory&apo ...

The lookat() function in three.js isn't functioning according to my requirements

Here is the code snippet I am working with: http://codepen.io/usf/pen/pGscf This is the specific section of interest: function animate() { //sun.rotation.x = t/1000; sun.rotation.y += 0.01; t += 0.1; earth.position.x = Math.sin((2*Ma ...

React 17 Form not registering the final digit during onChange event

I am currently experiencing an issue with a form that includes an input field of type "number." When I enter a value, the last number seems to be skipped. For example: If I input 99 into the box, only 9 is saved. Similarly, when typing in 2523, only 252 ...

Building custom components in Vue.js/NuxtJS can be a breeze when using a default design that can be easily customized through a JSON configuration

Currently, I am in the process of developing a NuxtJS website where the pages and components can either have a generic design by default or be customizable based on client specifications provided in the URL. The URL structure is as follows: http://localh ...