Issues with texturing in ThreeJS

I am currently working on a project in threejs that involves loading a .stl file. However, I have run into an issue where the loaded object automatically changes color from its original one. I would like to keep the original color of the object. What steps can I take to rectify this problem?

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 60, window.innerWidth/window.innerHeight, 1, 500 );

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild(renderer.domElement);

controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.center =  new THREE.Vector3();

// var geometry = new THREE.BoxGeometry( 3, 1, 1 );
// var material = new THREE.MeshBasicMaterial( { color: 'skyblue' } );
// var cube = new THREE.Mesh( geometry, material );
// scene.add( cube );

var loader = new THREE.STLLoader();
loader.load( 'js/novo/undefined.stl', function ( geometry ) {
    console.log(geometry);

    var mesh = new THREE.Mesh(geometry);
    mesh.scale.set( 0.1, 0.1, 0.1 );
    // mesh.rotation.set( - Math.PI / 2, Math.PI / 2, 0 );
    // mesh.scale.set( 0.3, 0.3, 0.3 );
    // mesh.receiveShadow = true;
    scene.add( mesh );
});

camera.position.z = 300;

var animate = function () {
    requestAnimationFrame( animate );
    renderer.render(scene, camera);
};

animate();

I would like the final result to:

Looking forward to hearing your suggestions!

Answer №1

To ensure your Mesh has a material applied, make sure to include it in the constructor.

var mesh = new THREE.Mesh(geometry, material);

If you create a Mesh without specifying a material, a default random colored BasicMaterial will be used as per the THREE.Mesh source code.

function Mesh( geometry, material ) {

    Object3D.call( this );

    this.type = 'Mesh';

    this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
    this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );

    this.drawMode = TrianglesDrawMode;

    this.updateMorphTargets();

}

To resolve this issue, be sure to create and assign a material when creating the Mesh instance.
For example:

// Create a red material
var myMaterial = new THREE.MeshBasicMaterial({color: 0xff0000});
// Create a Mesh with the red material applied
var mesh = new THREE.Mesh(geometry, myMaterial);

Answer №2

Learn how to customize the color or texture of your loader here

var loader = new THREE.STLLoader();
                    loader.load('./FA-FF/FA.STL', function (geometry) {
                        /* Implementing a different texture */
                        var material = new THREE.MeshPhongMaterial({ map: THREE.ImageUtils.loadTexture('img/wood.jpg') });
                       /* Applying a new color */
                        var material = new THREE.MeshPhongMaterial({ color: 0xAAAAAA, specular: 0x111111, shininess: 200 });

                        var mesh = new THREE.Mesh(geometry, material);
                        mesh.name = "first";
                        mesh.position.set(-1, 1, 0);
                        mesh.rotation.set(1.5707963267948963, -8.326672684688674, -1.570796326794894);
                        mesh.scale.set(0.005, 0.005, 0.005);
                        mesh.castShadow = true;
                        mesh.receiveShadow = true;
                        scene.add(mesh);
                    });

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

From PHP to JavaScript, the looping journey begins

Question I am attempting to display markers on a map using PHP to fetch the data, then converting it into JavaScript arrays for marker addition. Below is an example of my code: Database query require_once("func/connect.php"); $query = "SELECT * FROM sit ...

What causes items within an Array() to be interdependent? (Javascript)

Here is what I attempted: let array = Array(2).fill([]); array[0].push(1); Expected result: array = [[1], []] Actual result: array = [[1], [1]] Can someone explain why the second element is affected by the first in this scenario? Appreciate any help in ...

I'm interested in clicking on an image within a div to trigger a page refresh and then automatically hide the div once the page has refreshed

UPDATE 2 SITUATION To prevent access to quiz content until the page is refreshed, I am employing a semi-transparent image with a top-margin off-set. The following code functions flawlessly on one specific page and only once: JavaScript window.addEventL ...

The PHP plugin I created seems to be adding an unnecessary whitespace at the end of its output

New to the world of PHP, I challenged myself to create a simple PHP plugin that generates a text greeting based on the time of day for users. To use my plugin, simply drop the .php file into your 'includes' folder and insert a line where you want ...

Embedding Vue component into a traditional PHP/jQuery project

Currently, I have a large legacy web application that is primarily built using Codeigniter and jQuery. Our strategy moving forward involves gradually transitioning away from jQuery and incorporating Vuejs into the project instead. This process will involv ...

Disabling Firebase error logging for unsuccessful signInWithEmailAndPassword attempts

My current project involves setting up a login system using Firebase auth in NextJS. Strangely, when I call the login function with incorrect credentials, an error is logged to the console even though my catch statement for handling errors is empty. Is the ...

Real-time Updating of ChartJS Charts in Rails Using AJAX

I am currently working with Rails 5 and the latest version of ChartJS library (http://www.chartjs.org/docs/). My goal is to retrieve the most recent 20 items from the SensorReading model and update the Chart using setInterval and AJAX. I have successfull ...

Using JavaScript to compare arrays in order to display only the distinct outcome

Just starting out with JavaScript array matching! I've got two arrays, both with 11 elements each: txtfilename=['txt1','txt6','txt6','txt6','txt7','txt7','txt8','txt9',& ...

Alignment issue with ThreeJS Collada file

I'm currently diving into the world of ThreeJS and I am experimenting with loading collada files into a viewer. My journey began by replicating the code from the Elf colladaLoader demo. I successfully managed to display the model inside an 800px squa ...

Avoid having to refresh the page on create-react-app after uploading an image or file

Currently, my application is set up with 'create-react-app' and I am retrieving images from a folder within the 'src' directory. However, when a new image is uploaded through a form submission, it causes the page to reload as the image ...

What sets Import apart from require in TypeScript?

I've been grappling with the nuances between import and require when it comes to using classes/modules from other files. The confusion arises when I try to use require('./config.json') and it works, but import config from './config.json ...

The GET request on the Express route is malfunctioning, causing the Postman request to time out after getting stuck for some

My Express app seems to be experiencing some issues with the GET route. When making a request using Postman, the response gets stuck for a while before fetching. The GET route is properly set up with all necessary request parsers and the app initialized an ...

Troubleshooting Angular Reactive Forms: Issue with Binding Dynamic Select Dropdown Value

I currently have two arrays of data: AssociatedPrincipals, which contains previously saved data, and ReferencePrincipals, which consists of static data to populate dropdown controls. I am facing difficulties in displaying/selecting the previous value from ...

The data display in MUI-Datatable is experiencing an issue where it is unable to read properties of undefined, specifically when trying to split the data

Whenever I include data within the MuiDatatable, it triggers this error: Cannot read properties of undefined (reading 'split') Is there a solution to this problem so that the data can be properly displayed? To demonstrate the issue, I have se ...

What steps do I need to take to produce a laser beam illusion using additive blending?

I am attempting to replicate a laser beam effect found in this article: However, when I apply THREE.AdditiveBlending for blending, the color of the laser beam seems to blend with the background color. See image here: https://i.sstatic.net/rIG0e.png ( 3rd ...

Tips for integrating Google WebKit with AngularJS

Looking to enhance my application with Google WebKit functionality. My goal is to create a feature similar to Gmail's where hovering over the "+" symbol expands to display options such as "insert photos" and "insert links". I'm just starting out ...

Shared codes are compatible with both C and Javascript programming languages

Within the scope of this project, data will be retrieved from the server in either JSON or XML format. There are two separate client applications that will handle the data processing, with one being web-based and written in JavaScript, while the other is ...

Turn off color blending for certain objects in Three.js

I am currently working on a visualization tool for 2D objects in Three.js. My goal is to render a series of 2D shapes using an orthographic camera, with each larger shape appearing to "contain" the smaller ones. To achieve this effect, I have utilized the ...

The posenet TensorFlow model results in Node.js do not contain any position detail for coordinates "x" and "y"

I executed the posenet model on node v8.11.0. Below is the code snippet that I utilized. Unfortunately, the output results are not displaying the position of each pose; instead, it simply shows [Object]. It seems like there might be a canvas-related issue. ...

Display or conceal div based on chosen options

I am working on a feature that involves three dropdown select boxes, each containing different sets of demographic attributes. My goal is to show a score based on the combination of selections made by the user. For example, if a user chooses Male, 18-24, A ...