Creating a cube with unique textures on each face in three.js r81: What's the best way to achieve this?

After updating to the latest version of three.js, I encountered an issue where THREE.ImageUtils.loadTexture no longer works. As a result, I tried searching for examples of cubes with different faces, but they all utilized the outdated technique "new THREE.ImageUtils.loadTexture". Determined to find a solution, I attempted to create one using "new THREE.TextureLoader.load('texture1.png')". Here is my attempt:

<!DOCTYPE html>
<html lang="en>
    <head>
        <title>three.js webgl - geometry - cube</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
        <style>
            body {
                margin: 0px;
                background-color: #000000;
                overflow: hidden;
            }
        </style>
    </head>
    <body>

        <script src="library/threejs/build/three.js"></script>

        <script>
            var camera, scene, renderer;
            var head;
            var loader = new THREE.TextureLoader();
            init();
            animate();
            function init() {
                camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);
                camera.position.z = 400;
                scene = new THREE.Scene();
            materials = [
            new THREE.TextureLoader().load('textures/mob/zombie/zombie_headfront.png'),
            new THREE.TextureLoader().load('textures/mob/zombie/zombie_headback.png'),
            new THREE.TextureLoader().load('textures/mob/zombie/zombie_headleft.png'),
            new THREE.TextureLoader().load('textures/mob/zombie/zombie_headright.png'),
            new THREE.TextureLoader().load('textures/mob/zombie/zombie_headup.png'),
            new THREE.TextureLoader().load('textures/mob/zombie/zombie_headdown.png')];

    head = new THREE.Mesh(
            new THREE.BoxBufferGeometry(80, 80, 80, 1, 1, 1, materials),
            new THREE.MeshBasicMaterial({ map: materials })
    );
                scene.add(head);
                renderer = new THREE.WebGLRenderer();
                renderer.setPixelRatio(window.devicePixelRatio);
                renderer.setSize(window.innerWidth, window.innerHeight);
                document.body.appendChild(renderer.domElement);
                window.addEventListener('resize', onWindowResize, false);
            }
            function onWindowResize() {
                camera.aspect = window.innerWidth / window.innerHeight;
                camera.updateProjectionMatrix();
                renderer.setSize(window.innerWidth, window.innerHeight);
            }
            function animate() {
                requestAnimationFrame(animate);
                head.rotation.x += 0.005;
                head.rotation.y += 0.01;
                renderer.render(scene, camera);
            }
        </script>

    </body>
</html>

However, I ran into the following errors:

TypeError: offset is undefined

and

THREE.WebGLShader: Shader couldn't compile

as well as

THREE.WebGLShader: gl.getShaderInfoLog() fragment ERROR: 0:238:   
'mapTexelToLinear' : no matching overloaded function found 

If you have any insights on how to resolve these issues or can provide guidance on creating a cube with six distinct sides, that would be greatly appreciated! Thank you!

Answer №1

There is a lesser-known material in THREE.js called THREE.MeshFaceMaterial. Although it has been deprecated for some time, it still functions in r81.

// Creating an array of six standard materials
var materials = [
    new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("https://i.imgur.com/8B1rYNY.png")}),
    new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("https://i.imgur.com/8w6LAV6.png")}),
    new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("https://i.imgur.com/aVCY4ne.png")}),
    new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("https://i.imgur.com/tYOW02D.png")}),
    new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("https://i.imgur.com/nVAIICM.png")}),
    new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("https://i.imgur.com/EDr3ed3.png")})
];
var geometry = new THREE.BoxBufferGeometry(200, 200, 200);

// Using THREE.MeshFaceMaterial for the cube with the array as the parameter
mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));

See Demo

In essence, this method works by generating a THREE.BufferGeometry plane for each face of the cube and assigning a material to each face (mrdoob himself). If this approach becomes obsolete, you can manually construct a cube using 6 planes, group them under a null object to manipulate them collectively, and then assign materials individually to each plane.

If your cube faces are predetermined and can be pre-rendered into a texture, a more complex yet superior choice is to employ UV mapping.

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

transmitting comfort through events

To enhance my application, I am working on publishing a solace message to a topic and then passing it along to another part of the app for further processing using events. This entire process is happening within a single node.js process. While I understand ...

On Linux systems, Node.js in JavaScript interprets strings as objects only

I'm encountering an issue with my Discord.io bot. I am attempting to run it on a Linux server, but the Linux version of Node.js keeps treating the contents of a string as a separate object, leading to the following TypeError: TypeError: Object IT&apo ...

The animation function in A-frame causes entities to vanish when used with D3.js

Working with the animation property in D3.js has been a bit of a challenge for me. When I include the a-animation directly in the HTML section, everything works as expected. <a-box id="box" position="0 1 0" rotation="0 0 0" scale="1 1 1" color="#4CC3D9 ...

Step-by-step guide on clipping a path from an image and adjusting the brightness of the remaining unclipped area

Struggling to use clip-path to create a QR code scanner effect on an image. I've tried multiple approaches but can't seem to get it right. Here's what I'm aiming for: https://i.stack.imgur.com/UFcLQ.png I want to clip a square shape f ...

Attempting to bring in HTML through a helper, but Rails doesn't seem too thrilled about it

I have a form that triggers a remote GET request, leading to the display of a modal. The issue I'm facing is that multiple actions can utilize the same model, so I am attempting to employ a helper and jQuery to showcase different data based on what is ...

Is there a way to access the value of an IPC message beyond just using console log?

I am developing an app using electron and angular where I need to send locally stored information from my computer. I have successfully managed to send a message from the electron side to the angular side at the right time. However, I am facing issues acce ...

Throttle the RxJs interval based on the inner observables

Sorry if the way I am asking this question is not clear, I am having difficulty finding the right words to explain it. I am currently working on Selenium automation and here is how the process goes:- Go to a specific page Every 1 second, check if the pag ...

Having trouble with accessing an element that contains both onclick and text attributes in Selenium Webdriver?

The HTML code I'm dealing with includes this element: <a style="text-decoration:none; font-weight:normal;" href="javascript:void(0);" onclick="CreateNewServiceItemApproved();"> <img src="icons/ui/addnew.png"> <span style="color:# ...

Develop a JavaScript application that contains a collection of strings, and efficiently sorts them with a time complexity of O(nlog n)

Seeking assistance in developing a JavaScript program that contains an array of strings and must sort them efficiently in O(nlog n) time. Grateful for any guidance... ...

In the event that the hash consists of just one string, disregard any additional conditional statements

Currently, I am in the process of updating one of my coding playgrounds and facing some issues. If the user has only the "result" string in the hash like this... testhash.html#d81441bc3488494beef1ff548bbff6c2?result I want to display only the result ( ...

How can you stop queuing animations and timeouts in jQuery?

I'm facing a seemingly simple problem that I need help with. On my website, there's a hidden div.notification bar at the top. This bar can be displayed by adding either the success or warning class to it. There are two scenarios: either a messa ...

extract information from a document and store it in an array

As I delve into the realm of programming, I find myself grappling with the best approach to extract data from a file and store it in an array. My ultimate aim is to establish a dictionary for a game that can verify words provided by players. Despite my no ...

After executing "npm run dev" in Svelte and Vite, a common error message of "HTMLElement is not defined" might appear

Incorporating several web components into my Svelte project led to the appearance of an error message stating HTMLElement is not defined after running npm run dev (which actually translates to vite dev). The complete error message reads as follows: HTMLEl ...

The PHP script's header() function is failing to execute

Recently, I encountered an issue with my JavaScript code that calls a backend PHP script using AJAX. The main function of the AJAX request is to send user login data (username and password) to the PHP script, which in turn queries this information on the S ...

retrieving request headers using XMLHttpRequest

Is there a way for me to access my requestHeaders within the onload function? Any guidance on how to achieve this would be greatly appreciated. Many thanks! ...

Ways to eliminate redundant older React components within a different library

Having trouble with material-ui in my React project as I encounter this error. Error: Invalid hook call. Ensure hooks are only called inside the body of a function component. Check for: Possible mismatch of React and renderer versions (i.e., React DOM) ...

How can I create a custom validator in Angular 2 that trims the input fields?

As a newcomer to Angular, I am looking to create a custom validator that can trim the input field of a model-driven approach form. However, I have encountered difficulties during implementation. When attempting to set the value using setValue() within th ...

How to properly implement search functionality in a React table?

I recently implemented a search feature for my table in React to filter items fetched from an external API. Instead of making repeated calls to the API on each search, I decided to store the retrieved data in two separate useState hooks. One hook holds th ...

What are the necessary steps for incorporating Payment/Bank transactions into an e-commerce platform?

Right now, I'm utilizing HTML, CSS, jQuery, and some JavaScript to develop a website. As I work on creating the store section, I find myself unsure of how to incorporate payment methods and all related features. Are there any free "pre-built" systems ...

Disabling GPS with HTML5/phonegap: A step-by-step guide

Looking to create a function that can toggle GPS on and off for both iPhone and Android devices ...