What is the process for applying a texture image onto a shader geometry?

Seeking assistance in Three.js: I have successfully mapped a texture image to a plane geometry and rendered it in one scene. In another scene, I have a cube with shader material. Now, I need help incorporating the texture from the first scene onto the surface of the cube. Any guidance would be appreciated.

I have limited documentation on this topic and am relatively new to Three.js. Unsure about the necessary adjustments to my HTML file's vertex and fragment shaders after completing the initial setup as described earlier.

The first scene includes my texture image and plane geometry, while the second scene features the cube alongside the fragment and vertex shader scripts:

this.vertShader = document.getElementById('vertexShader').innerHTML;
this.fragShader = document.getElementById('fragmentShader').innerHTML;
var geometry = new THREE.BoxGeometry( 0.5, 0.5 );

var material = new THREE.MeshLambertMaterial( { color: "blue", wireframe: 
true} );
this.mesh = new THREE.Mesh( geometry, material );
this.scene.add( this.mesh );

var texture = new THREE.TextureLoader().load ('js/textures/earth.jpg');
var texMaterial = new THREE.MeshBasicMaterial( { map: texture } );
var texGeometry = new THREE.PlaneGeometry(1, 1);
this.texmesh = new THREE.Mesh(texGeometry, texMaterial);
this.texmesh.position.set(0,0,0);
this.texScene.add(this.texmesh);

vertex shader: varying vec2 vUv;

void main() {
    vUv = uv;

    gl_Position =   projectionMatrix * modelViewMatrix * 
vec4(position,1.0);
 }

fragment shader: uniform sampler2D texture;

varying vec2 vUv;

void main() {
    gl_FragColor = texture2D(texture, vUv);
}

I am aiming to apply the texture image seamlessly across the cube's surface.

Answer №1

In order to create a fragment shader, you need to declare a uniform variable of type sampler2D:

Vertex Shader:

varying vec2 vUv;

void main() {
    vUv = uv;
    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}

Fragment Shader:

precision highp float;

uniform sampler2D u_texture; // <---------------------------------- texture sampler uniform

varying vec2 vUv;

void main(){
    gl_FragColor = texture2D(u_texture, vUv);
}

A THREE.ShaderMaterial can be created using these shaders.

Begin by loading the texture:

var texture = new THREE.TextureLoader().load ('js/textures/earth.jpg');

Then define the set of Uniforms (in this case, there is only the texture uniform):

var uniforms = {
    u_texture: {type: 't', value: texture}
};

Lastly, create the material:

var material = new THREE.ShaderMaterial({  
      uniforms: uniforms,
      vertexShader: document.getElementById('vertex-shader').textContent,
      fragmentShader: document.getElementById('fragment-shader').textContent
});

The material can then be used like any other material, as shown in the example below:

…(Example continues)…

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

Keep things in line with async functions in Node JS

Hello, I am just starting out with NodeJs and I have a question. I am trying to push elements into an array called files based on the order of the urls provided, but it seems like I'm getting a random order instead. Below is the code I've been wo ...

Order modules in a specific sequence in Node.js

I am facing an issue where the invoke action is being called before the validate file function in my code. I have been trying to figure out how to ensure that validateFile is called before appHandler.invokeAction. Would using a promise be a suitable soluti ...

Is there a way to create a list of languages spoken using Angular?

I am in search of a solution to create a <select> that contains all the language names from around the world. The challenge is, I need this list to be available in multiple languages as well. Currently, I am working with Angular 8 and ngx-translate, ...

Problem with routing: Request parameters not being collected

I am currently working on a project to create a wikipedia clone. Initially, I set up an edit route that looks like this: router.get('/edit/:id', function(req, res){ var id = req.params.id; console.log(id); models.Page.findById(id, ...

What is the best way to upload an object in React using fetch and form-data?

Currently, I am facing an issue where I need to send a file to my express app as the backend. The problem lies in the fact that my body is being sent as type application/json, but I actually want to send it as form-data so that I can later upload this file ...

Saving JavaScript Object Notation (JSON) information from Node.js into MongoDB

Currently, I am successfully pulling weather data in JSON format from Wundground using their API. The next step for me is to store this data in MongoDB for future use. After retrieving the data and attempting to write it to a Mongo collection, I encountere ...

Custom HTML on Joomla causing carousel to vanish

I've encountered an issue with my Joomla website where my carousel images are disappearing. I have a code snippet from W3 Schools for an automatic banner that works perfectly fine when opened in a browser using Notepad++, but when inserted into a cust ...

Include a quantity dropdown menu on the cart page of your Shopify store's debut theme

Hey there! I'm currently customizing the Shopify Debut theme and I'm trying to incorporate a quantity selector as a dropdown on the cart page. Unfortunately, I'm encountering some issues with this implementation. I've managed to succes ...

Tips for Accessing Values in a Dynamic Array in Vue.js

ArrayOrdered :[ { name :"PRODUCT 1", price :"20", amount:"10", Total 1:" ", discount : "" , Total 2:" " }, { name :"PRODUCT 2", price :"50", amount:"20", Total 1:" ", discount : "" , Total 2:" " }, { name :"PRODUCT 3", price :"15.5", amount:"10", Total ...

Swap out the image backdrop by utilizing the forward and backward buttons

I am currently working on developing a Character Selection feature for Airconsole. I had the idea of implementing this using a Jquery method similar to a Gallery. In order to achieve this, I require a previous button, a next button, and the character disp ...

Using Material-UI with @emotion/cache in SSR results in consistently empty cache

After transitioning my React SSR from pure @emotion to material-ui 5.0, I encountered an issue where the styles no longer get extracted. The ID extraction in createExtractCriticalToChunks seems to be functioning correctly, but the cache.inserted object fro ...

The transmission of data from $http to php is not functioning properly

var app = angular.module("report", []); function index($scope, $http){ $scope.auth = function(){ $http({ url: '/index.php/users/auth', method: "POST", data: {login: $scope.login, password: $scope. ...

"Error: The .cssText method in Javascript is not working properly

I have been encountering an issue where the .cssText is not updating the HTML element referred to as .unveil. I implemented an event that when the container for .unveil is clicked, the .unveil element should become visible. However, upon clicking the .unve ...

Building a static website with the help of Express and making use of a public directory

It seems that I am facing a misunderstanding on how to solve this issue, and despite my efforts in finding an answer, the problem persists. In one of my static sites, the file structure is as follows: --node_modules --index.html --server.js --app.js The ...

Modify the heading color of elements in a class to a distinct color when the cursor hovers over the element

I currently have 3 heading elements: elem1, elem2, and elem3. When I hover over elem1, I want elem1 to turn yellow and elem2 and elem3 to turn purple. If I hover over elem2, I want elem2 to be yellow and the others to be purple. Once I release the hover, I ...

function not defined

(function($){ $.fn.slideshow = function(){ function init(obj){ setInterval("startShow()", 3000); } function startShow(){ alert('h'); } return this.ea ...

The display of the selected input is not appearing when the map function is utilized

I am attempting to use Material UI Select, but it is not functioning as expected. When I use the map function, the default value is not displayed as I would like it to be. However, it does work properly when using the traditional method. *** The Method th ...

What is the method for determining if a given point falls within a 3-dimensional cube?

I am currently seeking a method to determine whether a location is situated inside a rotated cube. To provide some context, I have access to the coordinates (x,y,z), rotation values (x,y,z), and dimensions (x,y,z). I am working with Javascript for this pr ...

Creating an HTML5 canvas that expands to cover the entire html document

After learning JavaScript, I decided to create a page on Github. Everything seems fine, except that the JS code for canvas doesn't scale to fit the entire HTML page. The particles only bounce off the initial window, leaving empty space when scrolling ...

When utilizing the data property within the useQuery() hook, an error may arise stating "Unable to

This problem has me scratching my head. The code snippet below is triggering this error: TypeError: Cannot read properties of undefined (reading 'map') When I use console.log() to check res.data, everything seems normal and there is data present ...