How can you incorporate a displacement map onto a mesh using the Three.js framework?

JSFiddle: http://jsfiddle.net/ma791nd8/1/

I'm encountering some challenges due to outdated tutorials and limited documentation, which is why I've decided to seek assistance here.

After reviewing one of the examples provided, I created a jsfiddle with updated syntax. However, I'm facing a CORS issue even though I have set up myTexture.crossOrigin = ''. Additionally, I can't figure out why it's not working in general. Any insights?

You can view a demo of the original example here: https://github.com/meetar/three.js-displacement-map

Here are my modifications in the JSFiddle version:

// scene setup
var renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(document.body.clientWidth, document.body.clientHeight);
document.body.appendChild(renderer.domElement);
var scene = new THREE.Scene();
// CAMERA

var fov = 45; // camera field-of-view in degrees
var width = renderer.domElement.width;
var height = renderer.domElement.height;
var aspect = width / height; // view aspect ratio
var camera = new THREE.PerspectiveCamera( fov, aspect );
camera.position.z = -200;
camera.position.y = -400;
camera.lookAt(scene.position);
// LIGHTS
ambientLight = new THREE.AmbientLight( 0xffffff );
scene.add( ambientLight );
// SHADERS
planeMesh = new THREE.Group();

var myTexture = new THREE.TextureLoader();
myTexture.crossOrigin = '';
myTexture.load('https://leveldev.files.wordpress.com/2012/12/heightmap.jpeg',
    function (myTexture) {
        var shader = THREE.ShaderLib[ "normalmap" ];
        var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
        uniforms[ "enableDisplacement" ].value = true;
        uniforms[ "enableDiffuse" ].value = true;
        uniforms[ "tDisplacement" ].value = myTexture;
        uniforms[ "tDiffuse" ].value = myTexture;
        uniforms[ "uDisplacementScale" ].value = 50;
        var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, wireframe: true };
        var material = new THREE.ShaderMaterial( parameters );

        var plane = new THREE.Mesh( geometry, material);
        planeMesh.add(plane)
        }
);

planeMesh.rotation.y = Math.PI;
scene.add(planeMesh);
// FUNCTIONS

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

Answer №1

The most recent version of Three.js, r73, now includes built-in displacement maps in the MeshPhongMaterial. Check out this easy example:

var loader = new THREE.TextureLoader();
var myDisplacementMap = loader.load( 'path/to/image.jpg' );

var material = new THREE.MeshPhongMaterial( {
    color: 0xffffff,
    //...
    displacementMap: myDisplacementMap,
    displacementScale: 10
} );

http://jsfiddle.net/cmn7z00b/

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

Optimizing Performance by Managing Data Loading in JavaScript Frameworks

I am new to JavaScript frameworks like React and Vue, and I have a question about their performance. Do websites built with React or Vue load all data at once? For example, if I have a page with many pictures, are they loaded when the component is used or ...

Ways to distinguish XmlHttpRequest Access-Control-Allow-Origin issues from regular network errors

When making an ajax request, there is a possibility of encountering an error, indicating a failure to establish communication with the intended target (no status code returned). To handle these errors, you can use the following code: var oXhr = new XMLHt ...

What is the process for altering the color of an HTML output depending on its values?

I created a simple HTML code to showcase some outcomes. The possible results are SUCCESS, Failure, and Still Failing. I want these results to be displayed with corresponding colors, such as green for SUCCESS, and red for both Failure and Still Failing. I ...

Error encountered during module build in Vue loader version 17.0.0 with Webpack version 5.74.0

I am encountering an issue while trying to integrate vue-loader into my SPA VUE APP. The error message I'm receiving is as follows: ERROR in ./app2.vue Module build failed (from ./node_modules/vue-loader/dist/index.js): TypeError: Cannot read prope ...

Although responseText functions properly, responseXML remains constantly null

I've searched through all available answers here and still can't find a solution. I'm confident that I haven't overlooked anything obvious. My issue involves loading map markers based on latitude and longitude coordinates. The problem ...

Whenever I attempt to include state in a React class that is declared as a constant, I consistently encounter the error message: "TypeError:

Apologies for the redundancy, but as a newcomer to React, I previously inquired about a similar issue and have since modified my code. My current challenge involves trying to access a state value within a const React class. Below is the excerpt from my Ar ...

Actility's LoraWan platform integrated with Node-Red

I am currently working on learning how to implement an HTTP GET request for the Actility platform in Node-RED. However, I keep encountering an error 401 indicating that the authorization bearer is missing. This is how my setup looks: https://i.sstatic.ne ...

Issues arise with Highcharts Sankey chart failing to display all data when the font size for the series is increased

I am currently working with a simple sankey chart in Highcharts. Everything is functioning correctly with the sample data I have implemented, except for one issue - when I increase the font size of the data labels, not all the data is displayed. The info ...

Error thrown by loader.js at line 582 of internal/modules/cjs/loader.js

Encountered this error message in the console: Error : Cannot find module. The detailed error is provided below. Any suggestions on how to resolve this? internal/modules/cjs/loader.js:582 throw err; ^ Error: Cannot find module 'C:\Users ...

Insert a scrollbar into the new popup window on Internet Explorer after the window has been opened

I am looking to enable scrolling in a pop-up window after it has been opened. While FireFox offers the 'window.scrollbars' property for this, Internet Explorer does not have a similar feature. Is there a way to add scrolling functionality in IE u ...

Unable to load page callback using NodeJS Express and Passport-facebook

I'm facing an issue with my Node.js application using Express for authentication via Facebook as the URL /auth/facebook/callback is not loading. Here are the dependencies versions: Express: 4.13.3 Passport: 0.3.0 Passport-facebook: 2.0.0 Below is th ...

React Select streamlines dropdown options for multi-selection by abbreviating names

Is there a way to shorten dropdown names when selected similar to the example shown in the image below https://i.sstatic.net/qUFP6.png This is the snippet of my code : multiValue: [ { value: "BUF", label: "BUF" }, ...

What is the method for linking images to URLs in my carousel?

I am in the process of revamping a confluence page that showcases a variety of visualizations. Here is the code snippet I am currently working with: <div class="carousel"> <img src="image1.jpg"> <img src="i ...

Ways to implement variables in Jade that are transmitted through res.render

Firstly, I would like to apologize for any errors in my English. In my router file, I have the following code: exports.index = function (req, res) { res.render('./game/main', {name:req.session.name, menuOp:'Home'}); } Additionally, ...

How can I protect my jQuery script from being accessed by "FIREBUG"?

I was tasked with creating a jQuery script as follows: function DeleteFile(_FileID) { //ajax method to delete the file } The FileID is stored in the 'rel' attribute of the list. However, when I call "DeleteFile" from Firebug using the fileId ...

Adjusting the height of a vertical slider in Vuetify2 is not customizable

I've been trying to adjust the height of a vertical slider in vuetify2, but setting it to "800px" or using style="height:800px" doesn't seem to work as intended. Even though the box within my grid expands, the height of the slider remains unchan ...

Switching classes in real time with JavaScript

I'm struggling to understand how to toggle a class based on the anchor text that is clicked. <div> <a id="Menu1" href="#">Menu</a> <div id="subMenu1" class="subLevel"> <p>stuff</p> </div> <div> <a i ...

Ways to prevent the use of the JavaScript increment (++) or decrement (--)

I have created two functions for a multi-step configuration on a webpage. protected clickNext(event:any, config:any) : any{ this.activeIndex++; } protected clickPrev(event:any, config:any) : any{ this.activeIndex--; } Here are the buttons: < ...

Attempting to modify the color of a selected Three.js object causes all objects in the scene to have their colors altered

For example, check out this JSFiddle link. The interesting part occurs during the mousedown event: var hits = raycaster.intersectObjects( [object1, object2, object3] ); if ( hits.length > 0 ) { console.log(hits[ 0 ].object) hits[ 0 ].object.m ...

Is it possible to eliminate additional properties from an object using "as" in Typescript?

I am looking for a way to send an object through JSON that implements an interface, but also contains additional properties that I do not want to include. How can I filter out everything except the interface properties so that only a pure object is sent? ...