Ways to eliminate the transparency from this area

https://i.sstatic.net/0PuOQ.png

How do I eliminate the clipped objects that have become transparent or prevent the object below it from being shown? I want it to look like solid cubes in the real world. This issue is specific to rendering when using javascript with three.js. HTML and CSS are working fine.

var scene, camera, renderer, cube;

var WIDTH = window.innerWidth;
var HEIGHT = window.innerHeight;

var SPEED = 0.001;

function init() {
    scene = new THREE.Scene();
    initLight();
    drawScene();
    initCamera();
    initRenderer();
    document.body.appendChild(renderer.domElement);
}

function initLight() {
    const light = new THREE.PointLight(0xFFFFFF);
    light.position.x = 50;
    light.position.y = 50;
    light.position.z = 130;
    scene.add(light);
}

function initCamera() {
    camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT, 1, 10);
    camera.position.set(1, 3, 5);
    camera.lookAt(scene.position);
}

function initRenderer() {
    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(WIDTH, HEIGHT);
    renderer.sortObjects = false;
}

function drawScene() {
    var material = new THREE.MeshLambertMaterial({ color: 0xFF6600 });
    var shape = new THREE.CubeGeometry(1, 1, 1);
    cube = new THREE.Group();
    for (var a = -10; a <= 10; a = a + 2) {
        for (var b = -10; b <= 10; b = b + 2) {
            for (var c = -10; c <= 10; c = c + 2) {
                var part = new THREE.Mesh(shape, material);
                part.position.set(a, b, c);
                cube.add(part);
            }
        }
    }
    scene.add(cube);
}
function rotateCube() {
    cube.rotation.x -= SPEED;
    cube.rotation.y -= SPEED;
    cube.rotation.z -= SPEED;
}

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

init();
render();
<script src="https://threejs.org/build/three.js"></script>

Answer №1

I made an adjustment to the PerspectiveCamera by bringing the near plane closer, setting it to 0.01 instead of 1, and included some additional code snippets to ensure your program runs smoothly.

The issue with the "transparency" effect you mentioned is caused by the cubes intersecting with the camera's near plane. By moving the plane closer to the camera, you essentially reduce the viewport size in the world, allowing it to fit more comfortably between the cubes.

Another factor to consider is backface culling, which hides cubes when viewed from the inside. You can turn off backface culling using material.side = THREE.DoubleSide, although this may result in rendering twice as much geometry.

var scene, camera, renderer, cube;

var WIDTH = window.innerWidth;
var HEIGHT = window.innerHeight;

var SPEED = 0.001;

function init() {
    scene = new THREE.Scene();
    initLight();
    drawScene();
    initCamera();
    initRenderer();
    document.body.appendChild(renderer.domElement);
}

function initLight() {
    const light = new THREE.PointLight(0xFFFFFF);
    light.position.x = 50;
    light.position.y = 50;
    light.position.z = 130;
    scene.add(light);
}

function initCamera() {
    camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT, 0.01, 10);
    camera.position.set(1, 3, 5);
    camera.lookAt(scene.position);
}

function initRenderer() {
    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(WIDTH, HEIGHT);
    renderer.sortObjects = false;
}

function drawScene() {
    var material = new THREE.MeshLambertMaterial({ color: 0xFF6600, side: THREE.DoubleSide});
    var shape = new THREE.CubeGeometry(1, 1, 1);
    cube = new THREE.Group();
    for (var a = -10; a <= 10; a = a + 2) {
        for (var b = -10; b <= 10; b = b + 2) {
            for (var c = -10; c <= 10; c = c + 2) {
                var part = new THREE.Mesh(shape, material);
                part.position.set(a, b, c);
                cube.add(part);
            }
        }
    }
    scene.add(cube);
}
function rotateCube() {
    cube.rotation.x -= SPEED;
    cube.rotation.y -= SPEED;
    cube.rotation.z -= SPEED;
}

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

init();
render();
<script src="https://threejs.org/build/three.js"></script>
    <script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/controls/OrbitControls.js"></script>

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

Contrasting element.setAttribute and element.style.setProperty differences

I am trying to dynamically change the value of a custom CSS variable using JavaScript. I initially attempted to use element.style.["--my-custom-var"] = value, but realized that it did not work for custom variables. After some research, I discover ...

Utilize JavaScript, jQuery, or Angular to incorporate identifications into <p> elements

I am working with a dynamically generated HTML document that contains several <p> tags with text inside. My goal is to be able to select a specific <p> tag when a user clicks on the text within it. However, I am restricted from adding ids to th ...

What is the best way to implement form validation and conditional markup using AngularJS?

What is the best way to display error messages using AngularJS and forms? I attempted to validate my form with the following code but it doesn't seem to work: <div class="form-group" ng-class="{'has-error': obj.title.$invalid}"> &l ...

Inject the css file into the PDFMake styling configuration

My current task involves converting a string with HTML markup into a PDF using the HTML-to-pdfmake and pdf make libraries. The HTML code includes numerous classes and ids, with corresponding styles defined in a CSS file. Rather than manually adding all the ...

Combining PageObjects with non-angular pages: is it possible?

I am currently working on writing protractor tests for our application. One specific challenge I have encountered is dealing with a non-angular page within an angular page as an iframe. The issue I am facing is that I cannot properly map fields from the n ...

Query for looping through JavaScript: what is the technique for extracting only number elements to create a fresh array?

I have a set of tasks that need to be automated in my daily workflow. The specific task requires: Receiving messages in my IM, and appending the first, second & third number from each link with a "|" delimiter. If there are only 2 numbers in the sequence, ...

what could be causing the failure of this url to load?

Here is some code I am working with: <span id="urlWindow" style="float:right;" value="http://www.mysite.com">Open Url</span> The sizeUrl variable contains the URL However, when using the following code, it doesn't load properly: var s ...

Concealing the map on the webpage using Javascript (iframe)

Here is an excerpt from my code: <div id='content'> <div id='map'></div> <iframe name="content-wrapper"></iframe> </div> <div class="sidebar"> <div class="container"> <h2 ...

Using MongoDB in a feathers.js Hook

I'm struggling to make a feathers.js hook wait for a MongoDB call to complete before proceeding. I've tried using returns and promises, but so far nothing has worked. How can I ensure the hook waits for the database query to finish? ...

I am encountering an issue where the useState hook is returning an undefined value on separate components, even after

When setting up a login context, I wrap all my routes with the context provider and pass the initial value using useState: <userContext.Provider value={{loggedUser, setLoggedUser}}> In LogInMenu.jsx, which is responsible for setting the loggedUser ( ...

How to search for a value in Firebase database and save it to an HTML table?

I am working on fetching specific values from my 'snapshot' and storing them if they exist. Below is the snippet of my code: function paydata(){ firebase.database().ref("pay/0/0/").once('value', function(snapshot){ var resp ...

I keep encountering the message 'Invalid type of argument: string cannot be assigned to a parameter of type never' within the useNavigationBuilder.tsx file. What could be causing this issue?

if (route?.name) { routeNames.push(route.name); } } else { route = state.routes[state.index]; routeNames.push( ...Object.keys(screens).filter((name) => route?.name === name) ); } An unexpected error has ...

Utilizing JSON to display multiple markers on a Google Map

How can I display multiple markers on a Google Map using JSON data? I have successfully added a single marker, but I'm facing issues with adding multiple markers. Below is the code for a single marker (which is working): var lat=position.coords.lati ...

Is the unavailability of nodejs's require function in this closure when using the debugger console due to a potential v8 optimization?

I am facing an issue with using the require function in node-inspector. I copied some code from node-inspector and tried to use require in the debugger console to access a module for debugging purposes, but it is showing as not defined. Can someone help me ...

The submission of an Angular form through the post method is not working

I am experiencing an issue with this angular code that is preventing the URL from being submitted via post. My goal is to send form details through SMS, requesting a call back via mobile. <div id="page7-container1" ng-app="amApp"> <h4 id="p ...

Track and display live updates of marker movement on Google Maps

Every 20 seconds, the database table gets updated with new data. I am trying to update the marker on the map with the new latitude and longitude. I attempted to run a query every 30 seconds to retrieve the latest record from the table and update the mark ...

The equivalent of ESM for resolving modules using the `createRequire` function with a specified

In the process of developing a JavaScript instrumentation engine, I am currently focused on traversing a source file's Abstract Syntax Tree (AST) and queuing imported modules for instrumentation in a recursive manner. In order to achieve this, it is c ...

Every time I try to install create-react-app, I keep encountering a frustrating 'network Socket timeout' error

$ npx create-react-app amazon-clone npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead. Creating a new React app in D:\js\faceboom. npm WARN config global `--global`, `--local` are deprecated. ...

In certain cases, the AngularJS $rootScope may not be properly updating in the resolve function

Strangely, the $rootScope.user variable in my resolve function is not fully assigned with data before the view.html template loads. Most of the time, when I use {{ $root.user.uid }} in my template, I can see the variable data, but occasionally it does not ...

Determining the optimal times to utilize traditional loops instead of array helpers

After writing in Javascript for some time, I've become quite comfortable with using array helpers. However, there have been moments where traditional for loops seem more practical and easier to work with compared to array helpers. Can you provide me w ...