Enhancing custom geometry with textures in Three.js

Trying to figure out how to apply a simple material with a texture map to a custom mesh? Look no further! Check out this demo I created to showcase what I'm attempting to do.

/// MATERIAL
var texture = new THREE.TextureLoader().load( "https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/crate.gif" );
var material = new THREE.MeshBasicMaterial( { 
    map: texture,
  side: THREE.DoubleSide
} );

// TRIANGLE
var geometry2 = new THREE.Geometry();
var v1 = new THREE.Vector3(0,200,0);
var v2 = new THREE.Vector3(0,0,-100);
var v3 = new THREE.Vector3(0,0,100);
geometry2.vertices.push(v1);
geometry2.vertices.push(v2);
geometry2.vertices.push(v3);
geometry2.faces.push( new THREE.Face3( 0, 1, 2 ) );
meshCustom = new THREE.Mesh(geometry2, material);
scene.add(meshCustom);

// CUBE
var geometry = new THREE.BoxBufferGeometry( 100, 100, 100 );
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );

Explore the demo here!

If you're wondering how to make the triangle match the cube's texture, UV coordinates are key. Implementation of this may seem tricky, but don't worry, we'll figure it out together.

https://i.sstatic.net/yk8fr.png

Answer №1

Something seems off with the texture on the triangle... Just to be sure, adjusting the UVs to fit your specific object could potentially resolve this:

Check out your updated fiddle

Here are the steps to follow:

//texture
    var texture2 = new THREE.TextureLoader().load( "https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/crate.gif" );


//material
    var material2 = new THREE.MeshBasicMaterial( { 
        map: texture2,
      side: THREE.DoubleSide
    } );

  // TRIANGLE
    var geometry2 = new THREE.Geometry();
    var v1 = new THREE.Vector3(0,200,0);
    var v2 = new THREE.Vector3(0,0,-100);
    var v3 = new THREE.Vector3(0,0,100);
    geometry2.vertices.push(v1);
    geometry2.vertices.push(v2);
    geometry2.vertices.push(v3);
    geometry2.faces.push( new THREE.Face3( 0, 1, 2 ) );

//manually setting UV coordinates
    geometry2.faceVertexUvs[0].push([
            new THREE.Vector2(0,0),        //adjust these values as needed
            new THREE.Vector2(0.5,0),
            new THREE.Vector2(0.5,0.5)
        ]);

//updating the UVs
    geometry2.uvsNeedUpdate = true;

Answer №2

Finally got it to work by adding UV coordinates to the Geometry. Special thanks to this helpful source:

Implemented this function and ran the geometry through it.

function assignUVs(geometry) {
    geometry.faceVertexUvs[0] = [];
    geometry.faces.forEach(function(face) {
        var components = ['x', 'y', 'z'].sort(function(a, b) {
            return Math.abs(face.normal[a]) > Math.abs(face.normal[b]);
        });

        var v1 = geometry.vertices[face.a];
        var v2 = geometry.vertices[face.b];
        var v3 = geometry.vertices[face.c];

        geometry.faceVertexUvs[0].push([
            new THREE.Vector2(v1[components[0]], v1[components[1]]),
            new THREE.Vector2(v2[components[0]], v2[components[1]]),
            new THREE.Vector2(v3[components[0]], v3[components[1]])
        ]);

    });
    geometry.uvsNeedUpdate = true;
}

This function automatically generates UV coordinates from the geometry, allowing textures with images to display on custom geometries.

Check out my updated functional jsfiddle link here.

https://jsfiddle.net/benaloney/L7js807k/9/

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

What is the best way to use an object as a key to filter an array of objects in JavaScript?

My data consists of an array of objects: let allData = [ {title:"Adams",age:24,gender:"male"}, {title:"Baker",age:24,gender:"female"}, {title:"Clark",age:23,gender:"male"}, {title:"Da ...

When changing the dropdown option on a separate page in React/Next JS, all checkboxes show the clicked style as a result of utilizing useState

I have implemented checkboxes for three different categories: "Types", "Price", and "Categories". They function correctly, with data being passed to a separate checkbox component without any issues. The problem arises when I click a checkbox and then inte ...

The process of connecting a user from a firestore database

Currently, I am working on developing a posting platform using Vue and Firebase. When a user creates a post, their username will be showcased alongside the post. An example would be: Created by user1 Everything is functioning smoothly in this aspect. No ...

Having trouble with your Ajax call to an express route?

Trying to initiate an ajax call from a JavaScript file to an express route within a Node.js application, while keeping in mind that the JavaScript file is also part of the same Node.js application. Encountering an issue where the data passed to the route ...

Ways to connect a button to a Bootstrap 5 tab class

I am trying to find a way to directly link to a specific tab using a Bootstrap 5 button class. I have attempted to incorporate the solution provided in the following resource: Twitter Bootstrap 5 Tabs: Go to Specific Tab on Page Reload or Hyperlink Unfo ...

Encountering the issue of receiving "undefined" as the object in React code

As a beginner in React JS, I am faced with the task of retrieving data from a URL in JSON format. Despite my efforts, I continue to receive a console feedback that says Rovers: undefined. How can I modify my code to achieve the desired output like this ...

Rotate the image using the handler, not by directly manipulating the image itself

I need help rotating the image using a handler instead of directly on the image itself. I do not want to rotate the image when clicking and rotating it directly. Please do not suggest using Jquery UI rotatable because resizing the image with Jquery UI resi ...

Trouble with _.keys function in Firebug - not detecting all items

I currently have a post stored in $scope.mydata within the controller. I pass this data as a parameter to a service that returns a function. The service looks like: module.factory('myservice', function () { return function servicefunction(m ...

Retrieve the Mongoose constructor information during the pre-save function

I am working with a schema that looks like this: const CustomerSchema = new Schema({ email: { type: String, required: true, unique: true }, flags: { marketingConsent: { type: Boolean, required: true }, }, }); When creating a new customer: co ...

Using jQuery to Decode the XML Document Containing National Threat Level Data

Recently, I've been experimenting with using jQuery to extract data from the DHS Threat Level found in their XML file. However, despite my efforts, I haven't been able to make it work. As a newcomer to Javascript and non-presentational jQuery, I& ...

A guide on invoking a web method from an aspx.vb page in VB.net

My goal is to call a WebMethod from my aspx.vb file. Below is the syntax of my WebMethod located in Default.aspx.vb: <System.Web.Services.WebMethod()> _ <ScriptMethod(UseHttpGet:=True, ResponseFormat=ResponseFormat.Json)> _ Public Shared Funct ...

Any ideas on how to format a date for jQuery Datepicker?

Currently, I have implemented two different datepickers on my website, but I am interested in switching to jQuery's Datepicker for a more unified solution. Here is the current format that I am sending to our backend API: However, I would prefer to i ...

Encountering an Error during the Installation of MapBox SDK in React Native

After creating a React Native project with Expo using expo init MapTry, I encountered an issue while trying to install the MapBox library. Despite following the installation guide at https://github.com/rnmapbox/maps#Installation, I faced an error message w ...

jQuery not getting desired response from AJAX GET request

I'm currently working on a project that involves displaying the member list of all users using AJAX get request. Everything seems to be functioning properly, but the content appended to my HTML is not responding to another jQuery script. Is there a w ...

What is the best way to retrieve the value of a selected button from a v-btn-toggle?

<v-btn-toggle v-model="toggle_one"> <v-btn flat> CAD50 </v-btn> <v-btn flat> CAD100 </v-btn> <v-btn flat> CAD1000 </v-btn> <v-btn flat> CAD10000 </v-btn> ...

Canvas loading may be restricted for Aframe / Three.js Tainted canvases

I am currently developing an application with Aframe that involves fetching images stored on AWS. Initially, I was consistently facing CORS rejection issues. After resolving that problem, my images are now passing CORS validation most of the time, but occ ...

Is there a way for me to display a customized error message using antd components?

During the registration process using React and Antd, if the backend returns the error message "user already registered" after clicking on "Sign up", it should be displayed in the form. You can customize the display as shown below: An example of how the u ...

What is a common mistake when using refs in React?

I've recently started diving into React. I've seen conflicting opinions on using refs - some sources claim it's a bad practice altogether. Can someone clarify this for me? Is it harmful to attach refs to child components in order to access ...

Rendering content conditionally using react technology

There is a functional component that receives two items as props. The properties can have values like `undefined`, `""`, `null`, `"null"`, or a valid string (e.g. `"test"`). The goal is to conditionally render these props based on their values. If both ` ...

The save button click handler is not triggering JQuery Validation

I've been attempting for hours to get the validation working, but without success. I have added the name attribute to the input element and included script sources as well. Even after firing the validate method, the contents are still not being valida ...