The challenge of rendering in Three.js

After configuring my code to render a geometry, I discovered that the geometry only appears on the screen when I include the following lines of code related to control:

controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.addEventListener('change', render );
controls.target = new THREE.Vector3(0, 0, 0);

If I attempt to remove these lines, the geometry disappears. Below is the complete code:

<html>
<head>
    <title>3D Model Example</title>
    <script src="Libraries/threejs/Three.js"></script>
    <script src="Libraries/threejs/Detector.js"></script>
    <script src="Libraries/threejs/BufferAttribute.js"></script>
    <script src="Libraries/threejs/BufferGeometry.js"></script>
    <script src="Libraries/threejs/EdgesHelper.js"></script>
    <script src="Libraries/threejs/OrbitControls.js"></script>

</head>

<body>
<p id="stats"></p>

<div id='maincanvas' style="border: 1px solid black; width: 500px; height:  500px"></div>
<input type="button" onClick="test()" value="test"/>
<input type="button" onClick="render()" value="render"/>

<script type="text/javascript">

    var container, testbox, scene, camera, renderer, controls, scene_text, raycaster, projector, mouse2D;

    function init()
    {

        // Setting up the scene
        scene = new THREE.Scene();

        // Camera configuration
        var SCREEN_WIDTH = window.innerWidth - 5, SCREEN_HEIGHT = window.innerHeight - 5;

        var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20;
        camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
        var r = 4, phi = Math.PI / 4, theta = Math.PI / 4;
        camera.position.set(r * Math.cos(phi) * Math.sin(theta), r * Math.sin(phi), r * Math.cos(phi) * Math.cos(theta));

        // Renderer setup
        if (Detector.webgl) {
            renderer = new THREE.WebGLRenderer({antialias: true});
        }
        else {
            renderer = new THREE.CanvasRenderer();
        }
        renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
        renderer.autoClear = false;

        // Adding renderer to the container
        container = document.getElementById('maincanvas');
        container.appendChild(renderer.domElement);

        // controls = new THREE.OrbitControls(camera, renderer.domElement);*** if remove controls geometry is not visible
        // controls.addEventListener('change', render );
        // controls.target = new THREE.Vector3(0, 0, 0);

        // Adding lights to the scene
        var light1 = new THREE.PointLight(0xffffff);
        light1.position.set(0, 1000, 1000);
        scene.add(light1);
        var light2 = new THREE.PointLight(0xffffff);
        light2.position.set(0, -1000, -1000);
        scene.add(light2);

        // Creating the geometry of the object
        geometry0 = new THREE.Geometry();
        geometry0.vertices = [new THREE.Vector3(0.5, -0.5, 0.5), new THREE.Vector3(-0.5, -0.5, 0.5), new THREE.Vector3(-0.5, -0.5, -0.5), new THREE.Vector3(0.5, -0.5, -0.5),
                              new THREE.Vector3(0.5, 0.5, 0.5), new THREE.Vector3(-0.5, 0.5, 0.5), new THREE.Vector3(-0.5, 0.5, -0.5), new THREE.Vector3(0.5, 0.5, -0.5)];
        geometry0.faces =
        [new THREE.Face3(3, 2, 1), new THREE.Face3(3, 1, 0), new THREE.Face3(4, 5, 6), new THREE.Face3(4, 6, 7), new THREE.Face3(0, 1, 5), new THREE.Face3(0, 5, 4),
         new THREE.Face3(1, 2, 6), new THREE.Face3(1, 6, 5), new THREE.Face3(2, 3, 7), new THREE.Face3(2, 7, 6), new THREE.Face3(3, 0, 4), new THREE.Face3(3, 4, 7)];
        geometry0.computeFaceNormals();
        geometry0.computeVertexNormals();
        var material0 = new THREE.MeshBasicMaterial({ color: 0xD1740A, transparent: true, opacity: 0.5 });
        mesh0 = new THREE.Mesh(geometry0, material0);
        scene.add(mesh0);
        egh0 = new THREE.EdgesHelper(mesh0, 0x000);
        egh0.material.linewidth = 2;
        scene.add(egh0);

    }

    function render()
    {
        renderer.clear();
        renderer.render(scene, camera);
    }

    function test()
    {
        init();
        render();
    }
</script>

</body>

</html>

Answer №1

It appears that your camera's position may not be set correctly, causing it to look in the wrong direction. Your object is currently positioned at (0,0,0), so adjusting the camera's position to face the right direction should resolve the issue.

To fix this, try setting the camera's position to something like:

camera.position.set(0,0,10);

In addition, if you are working on animations, it is recommended to add the following code at the end of the render function. However, if you do not have any animations, you can ignore this step:

requestAnimationFrame(render);

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

How can you access and utilize the inline use of window.location.pathname within a ternary operator in

I need assistance with writing a conditional statement within Angularjs. Specifically, I want to update the page to have aria-current="page" when a tab is clicked. My approach involves checking if the tab's anchor href matches the current window' ...

JavaScript code for opening and closing buttons

I created a button that successfully opens, but I am struggling to figure out how to close it. Can someone assist me with this? Additionally, I have one more query: How can I remove the border when the button is clicked? document.getElementById("arrowb ...

What is the method for incorporating a variable in MapReduce?

I have the following MapReduce script that I'm working with: splitAndGroupServices = function(groupMembers) { var mapFunction = function() { for(var idx in this.services) { var service = this.services[idx]; if(service.mem ...

Creating an Image slideShow with only one Image - making it slide on itself

Apologies for this confusing and vague question. Imagine I only have a single image, and I want to create a slideshow using technologies like Angular, jQuery, JavaScript, or just CSS. What I am aiming for is when the user clicks on my slide button, the i ...

Tips for establishing communication between a React Native webView and a React web application

I am currently working on establishing communication between a webView in react-native and a web-app created with React-360 (and React). I am utilizing the react-native-webview library and following a guide for creating this communication. You can find the ...

Trigger a refresh of the Angular app by clicking a button

Recently, I embarked on developing a single-page application that allows users to input data in a text box and navigate to another page. While designing the second page, I aimed to incorporate a home button that would not only return me to the initial view ...

The depth map for Three.JS MeshDepthMaterial appears to have uneven distribution

I'm currently experimenting with rendering depth maps of scenes using three.js For an example, check out this link: The quality of the depth map is affected by the careful setup of the scene, as shown here: camera.position.z = 30; camera.near = 0.1 ...

Retrieving information from an array and displaying it dynamically in Next.js

I've been diving into the Next.js framework lately and I've hit a roadblock when it comes to working with dynamic routes and fetching data from an array. Despite following the basics of Next.js, I'm still stuck. What am I looking for? I ne ...

How to have multiple versions of grunt coexisting on a single machine

I am involved in two different projects that have unique requirements for Grunt versions: Project A specifically needs Grunt v0.3.2 Project B requires Grunt v0.4.1 Both of these projects are managed in separate workspaces. Currently, I have Grunt v0.4. ...

How to remove an event listener when e.target points to a hyperlink

element, I encountered an issue using a slideshow component sourced from our components library. This component receives swipe events from a utility function that is initialized upon mounting. The problem arose while testing on a mobile phone - tapping a ...

Is there a way to enable data-add-back-btn using jQuery script?

Currently, I am utilizing jQuery 1.9.1 and jQuery Mobile 1.3.1 to define multiple pages within my project setup: <div id="q1" data-role="page" data-add-back-btn="false" data-back-btn-text="Home"> <div data-role="header" data-position="fixed" ...

Tips for using MatTableDataSource in a custom Thingsboard widget

After creating multiple custom Thingsboard widgets, I've discovered that I can access a significant portion of @angular/material within my widget code. While I have successfully implemented mat-table, I now want to incorporate pagination, filtering, a ...

How can I retrieve the height of a dynamically generated div in Angular and pass it to a sibling component?

My setup consists of a single parent component and 2 child components structured as follows: Parent-component.html <child-component-1 [id]="id"></child-component-1> <child-component-2></child-component-2> The child-compo ...

Hmm, JavaScript is throwing a JSON parse error related to single quotes. But where exactly is

When using an upload php script with AS3 and now with JavaScript, I encountered a test feature that should return this if everything is okay: {"erro":"OK","msg":"","descr":"op:ini,urlArq:\/Library\/WebServer\/Documents\/www\/sintr ...

Is there a way to automatically populate textbox values using a MySQL query response when the dropdown selection is changed?

How can I make the fields customer_address, customer_city, customer_state, and customer_zip autofill upon changing the selection in the dropdown for customer_name? I've searched everywhere but cannot find a solution. Your assistance would be greatly ...

Is it feasible to transmit an image file to PHP using AJAX?

I'm attempting to utilize AJAX to send an image file along with other text information. However, I am encountering difficulties with the file part and am struggling to comprehend how to resolve it. Below is the JavaScript code snippet: //The user ...

Clicking on a React Material UI ListItem

I am trying to develop a clickable country list with icons next to each ListItem. However, I am facing an issue where only one item can be selected at a time in a single click. Upon clicking a new item, the previously selected one gets deselected first. He ...

Deactivated the UpdateProgress functionality for the entire webpage

After exploring various options, I came across this solution: Is there a way to disable UpdateProgress for certain async postbacks? However, implementing this solution seems to prevent my controls from loading altogether! In my master page, there is an U ...

Utilizing global variables in Vue.js while working with the CLI template

How can I create a global variable in my Vue.js app that is accessible by all components and modifiable by any of them? I am currently utilizing the CLI template. Any recommendations on how to achieve this? Appreciate your assistance. Dhiaa Eddin Anabtaw ...

When you try to import a component, it may result in a blank page displaying an error message stating: "TypeError: Cannot set property 'components'

One interesting feature is the Vue component named DisplayContent, <template> <div></div> </template> <script lang="ts"> import { Vue, Component } from "vue-property-decorator"; import Home from "@/ ...