Three.js - creating transparent materials that only display the background, not the inner sides of objects

I am interested in applying a transparent material to the front-side faces of a geometry. It's a fairly simple process:

var normal = new THREE.MeshNormalMaterial();
            normal.side = THREE.BackSide;
    var materials = [
                normal,
            new THREE.MeshBasicMaterial( { transparent: true, opacity: 0 } )
            ];

    for( var i = 0; i < geometry.faces.length; i++ ) {
                geometry.faces[ i ].materialIndex = 0;
            }
    //a 'hole' to look inside
            geometry.faces[ 0 ].materialIndex = 1;
            geometry.faces[ 1 ].materialIndex = 1;
            mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ) );

Example link on Codepen: http://codepen.io/pyort/pen/egqbLY

However, there is a twist: when viewing the front-side of a face, I want to display what is underneath the geometry, not the backside.

It may be challenging to explain in simple terms, so here is a visual representation: https://i.sstatic.net/KKf0L.png

My goal is to create a 'portal' effect, where looking from one side gives the appearance of depth, but from other angles it appears super thin. How can I achieve this effect? Should I use a shader or mirror techniques?

Thank you.

Answer №1

Consider trying out this code snippet:

// create the interior cube
let geometryInside = new THREE.CubeGeometry(2,2,2);
let materialInside = new THREE.MeshLambertMaterial({
    transparent: true,
    color: 0xff0000,
    side: THREE.BackSide
}); 

let meshInside = new THREE.Mesh(geometryInside, materialInside);
scene.add(meshInside);

// create the invisible cloak (box with a hole)
let geometryCloak = new THREE.BoxGeometry(2,2,2);
geometryCloak.faces.splice(4, 2); // create a hole by removing top two triangles

let materialCloak = new THREE.MeshBasicMaterial({
    colorWrite: false
});

let meshCloak = new THREE.Mesh(geometryCloak, materialCloak);
meshCloak.scale.set(1,1,1).multiplyScalar(1.01); // slightly larger than inside cube
scene.add(meshCloak);   

You can view live examples at

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 we develop a strategy to select products based on specific features while keeping costs minimized?

I've got a collection of products with varying costs and features. Each product offers a unique set of features. I'm in need of an algorithm that, when given the specific features I desire, can recommend the most cost-effective combination of pr ...

Utilizing a function as a value in React state (setState) compared to defining state with constructor in a class and utilizing a state object

Can someone help me understand the concept of state in React better? I'm confused about the differences between these two implementations: This: class Todo extends ... { constructor (){ super() this.state = { ... } } } And This: class Todo extend ...

Troubles with data tables, pagination, and selecting rows

My application features a datatable with pagination. When a user selects a row in the table, a report is displayed below it that can be edited. If the user attempts to select another row without saving any pending edits, they are given a warning and the op ...

Dealing with text changes in JQuery inputs: best practices

Although this question has been raised numerous times, a definitive answer remains elusive. My goal is to trigger a process (such as an ajax call) when a user types into an input field. Initially, I attempted to utilize the onchange event, but it failed to ...

`Why won't the checkbox uncheck when the dropdown is changed in jQuery?`

I have a roster of users, each with a unique checkbox for selection. When I adjust the dropdown menu, a new group of users is chosen and marked as selected. However, I am struggling to uncheck the previously selected checkboxes based on the last dropdown c ...

The initiation of jQuery animation through user interaction hinges on the completion of the preceding animation

In my project, I've designed a timeline that offers users the ability to zoom in and out by simply clicking on corresponding buttons. Since the timeline is too large to fit entirely on the screen, it is contained within a scrollable div. To ensure tha ...

Issue with a stationary directional light tracking the movement of a rotating object and/or changes in the camera perspective

I've been facing a challenge in implementing a day-night cycle with a directional light in an Earth model using custom shaders. Everything seems to work fine with the night and day maps, as well as the light, as long as I don't manipulate the cam ...

Issue occurred while trying to set the value from an API call response in the componentDidMount lifecycle method

There is a boolean variable disableButton: boolean; that needs to be set based on the response received from this API call: async getDocStatus(policy: string): Promise<boolean> { return await ApiService.getData(this.apiUrl + policy + this.myEndpo ...

Unravel the HTML entities using jQuery

Is there a way to decode HTML entities using jQuery similar to the PHP function htmlspecialchars_decode? Here is the code I am currently using: if (jQuery.trim(jQuery("#push_alert").val()) != "") { alert = jQuery("#push_alert").val(); } Whenever the ...

How to display currency input in Angular 2

Is there a way to dynamically format input as USD currency while typing? The input should have 2 decimal places and populate from right to left. For example, if I type 54.60 it should display as $0.05 -> $0.54 -> $5.46 -> $54.60. I found this PLUN ...

Callback after completion of a for loop in Angular TypeScript

During the execution of my javascript async function, I encountered a situation where my printing code was running before the div creation. I needed to ensure that my print code would run only after the completion of the for loop, but I struggled to find a ...

Assistance required in designing a unique shape using Three.js

https://i.sstatic.net/pmHP2.png Hello there! I could use some assistance with replicating the 2D shape shown in the image above using three.js. Specifically, I'm encountering some difficulty with incorporating the subtle curvature seen on the inner l ...

Typescript is requesting an index signature for a nested object that has been validated by Zod and is being received from an API request

This project uses Typescript 4.4.4, Next.js 11.1.2, and Zod 3.9.3. Typescript is throwing an error that says: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type <Review Type> ...

What is the best way to use an Infinite scroll plugin to automatically fetch additional data from a database as the user scrolls down

In my Laravel Blade View, I am showcasing around 280 products from the database using the code snippet below. @if (get_setting('best_selling') == 1) <section class="mb-4"> <div class="container"> ...

PHP's 'include' function is now being ported into modern Javascript as a new method

As the library of JS frameworks continues to expand, I'm wondering if there is a simple JS replacement or alternative for PHP's 'include' function. Is PHP include still a relevant method for including chunks of code, or are there better ...

converting nested object structures in typescript

I'm trying to flatten a nested object in my Loopback and Typescript controller Here's the structure of my model : export class SampleModel { id: number; code: number; guide?: string; gradeData?: string; } Take a look at this example obj ...

Is it necessary for React to pass onClick as props to sub components?

Attempting to activate an onClick function within a sub-component by including the onClick in the parent component did not yield the desired outcome. // parent component class MainForm extends Component { // code here handleClick = () => { con ...

Setting up a function in React to utilize an image stored in state

I have a function in my react component for image classification that retrieves the image from the img tag using document.getElementById: const img = document.getElementById('animal_image');. The image uploaded via the file input updates the sta ...

What is the best way to initialize a value asynchronously for React context API in the latest version of NextJS, version

Currently, I'm working on implementing the React context API in my NextJS e-commerce application to manage a user's shopping cart. The challenge I'm facing is how to retrieve the cart contents from MongoDB to initiate the cart context. This ...

Guidelines for incorporating Angular variables into jQuery scripts

I have a form with an input field that dynamically generates a list of names using Angular. My goal is to turn each name into a clickable link that will submit the form with that specific name as the input value. <form method="POST" action="/results/" ...