The textureLoader seems to be malfunctioning when trying to load a normal map

Having an issue loading a texture in three.js for use as a normal map. No errors are being reported, but the texture fails to load, resulting in a black sphere.

import * as THREE from 'three';

/** Setting up the scene. */
const canvas = document.querySelector('#canvas');
const scene = new THREE.Scene();
const textureLoader = new THREE.TextureLoader();

/** Creating a sphere. */
const geometry = new THREE.SphereBufferGeometry(.5, 64, 64);
const material = new THREE.MeshStandardMaterial({
  metalness: 0.7,
  roughness: 0.2,
  normalMap: textureLoader.load('https://res.cloudinary.com/axiol/image/upload/v1617884764/CodePen/normalMap.png'),
  color: new THREE.Color(0x292929)
});
const sphere = new THREE.Mesh(geometry, material);
scene.add(sphere);

/** Setting the scene dimensions. */
const sizes = {
  width: window.innerWidth,
  height: window.innerHeight
};

/** Adding some light. */
const pointLight = new THREE.PointLight(0xffffff, 0.1)
pointLight.position.x = 2
pointLight.position.y = 3
pointLight.position.z = 4
scene.add(pointLight)

window.addEventListener('resize', () => {
  sizes.width = window.innerWidth
  sizes.height = window.innerHeight

  camera.aspect = sizes.width / sizes.height
  camera.updateProjectionMatrix()

  renderer.setSize(sizes.width, sizes.height)
  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
});

/** Positioning the camera. */
const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height, 0.1, 100);
camera.position.x = 0;
camera.position.y = 0;
camera.position.z = 2;
scene.add(camera);

/** Rendering the scene. */
const renderer = new THREE.WebGLRenderer({
  canvas: canvas,
  alpha: true
});
renderer.setSize(sizes.width, sizes.height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.render(scene, camera);

Unable to identify the issue causing the texture to not load. Any insights?

Answer №1

You are tasked with rendering a scene using a normal map that is currently not fully loaded. To address this issue, follow these steps:

/** Building the scene */
const canvas = document.querySelector('#canvas');
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xffffff);
const textureLoader = new THREE.TextureLoader();

/** Creating a sphere */
const geometry = new THREE.SphereBufferGeometry(0.5, 64, 64);
const material = new THREE.MeshStandardMaterial({
  metalness: 0.7,
  roughness: 0.2,
  normalMap: textureLoader.load('https://res.cloudinary.com/axiol/image/upload/v1617884764/CodePen/normalMap.png', render),
  color: new THREE.Color(0xffffff)
});
const sphere = new THREE.Mesh(geometry, material);
scene.add(sphere);

/** Setting sizes based on window size */
const sizes = {
  width: window.innerWidth,
  height: window.innerHeight
};

/** Adding light */
const pointLight = new THREE.PointLight(0xffffff, 1);
pointLight.position.x = 2;
pointLight.position.y = 3;
pointLight.position.z = 4;
scene.add(pointLight);

window.addEventListener('resize', () => {
  sizes.width = window.innerWidth;
  sizes.height = window.innerHeight;

  camera.aspect = sizes.width / sizes.height;
  camera.updateProjectionMatrix();

  renderer.setSize(sizes.width, sizes.height);
  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});

/** Placing the camera */
const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height, 0.1, 100);
camera.position.x = 0;
camera.position.y = 0;
camera.position.z = 2;
scene.add(camera);

/** Rendering the scene */
const renderer = new THREE.WebGLRenderer({
  canvas: canvas
});
renderer.setSize(sizes.width, sizes.height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
render();

function render() {
  renderer.render(scene, camera);
}
body {
  margin:0
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="70041802151530405e4142475e40">[email protected]</a>/build/three.js"></script>
<canvas id="canvas"></canvas>

Make sure to include the render() call in the onLoad() callback of the TextureLoader.load() method.

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 reason behind external JavaScript files being able to access the functions of other external JavaScript files, and what measures can

While I may not be an expert in JavaScript, I find it intriguing that within a project containing 3 JavaScript files, any of these files can access functions from the others. The real puzzle lies in figuring out how to prevent this from happening. For in ...

Angular 6 - Consistently returning a value of -1

I'm facing an issue with updating a record in my service where the changes are not being reflected in the component's data. listData contains all the necessary information. All variables have relevant data stored in them. For example: 1, 1, my ...

Error: 'discord not defined' encountered when using vscode and powershell

I'm still learning the ropes of javascript, and while attempting to link discord with VSCode (using windows powershell), I'm using the following code: const Discord = require (discord.js) ; const client = new Discord.Client(); clien ...

Troubleshooting problem in Vercel with Next.js 13 application - encountering "Module not found" error

Encountering a deployment issue with my Next.js 13 application on Vercel. I recently implemented the Parallel Routes feature of Next in my codebase. While pushing the changes to create a new pull request on GitHub, the branch's deployment on Vercel is ...

Can anyone recommend an easy regular expression to validate date format patterns?

While searching for regex patterns to validate date values in a specific format, I came across numerous options. However, I prefer to allow users to input their own custom date patterns such as: d-mm-yyyy MM/dd/yy yyyy.mm.d I am looking for a ...

What could be the reason for Object.assign failing to update a key in my new object?

Function handleSave @bind private handleSave() { const { coin, balance } = this.state; console.log('coin', coin); console.log('balance', balance); const updatedCoin = Object.assign({ ...coin, position: balance }, coi ...

What could be the reason behind my inability to initiate this PHP file through jQuery/AJAX?

I'm experiencing an issue with a piece of PHP code (located at ../wp-content/plugins/freework/fw-freework.php). <div id="new-concept-form"> <form method="post" action="../wp-admin/admin.php?page=FreeWorkSlug" class="form-inline" role ...

Animate the smooth transition of a CSS element when it is displayed as a block using JQuery for a

I have implemented the collapsible sections code from W3 School successfully on my website. Now, I am trying to achieve a specific functionality where the "Open Section 1 Button" should slide down with a margin-top of 10px only if the first section "Open S ...

Unable to create a post request using jQuery with a JSON payload

When using the Chrome REST service, I successfully make a post request to a specific URL by sending a JSON string in the body and setting the content type as application/json. However, when trying to achieve the same with jQuery, I encounter some issues. ...

Addon for Three.js in Blender not appearing on Addons screen for Windows 7 and Windows Vista users

Is there anyone who has successfully been able to make the three.js import export addon in Blender work on either Windows 7 or Windows Vista? I have attempted this on two different computers. For Windows 7, I placed the files in the following directory ( ...

Attempting to retrieve XML/JSON

I am struggling with extracting the first 15 words from a file using the API. I have attempted to do it with both XML and JSON, but keep encountering this error: XMLHttpRequest cannot load No 'Access-Control-Allow-Origin' header is present on th ...

Unable to animate a second click using jQuery/CSS

I'm having an issue with animating on click using CSS. The animation works fine on the first click, but it doesn't work on the second click. This is because the click event is being overridden by jQuery to enable the dropdown menu to open onClick ...

The inability to access data from an API is a result of the lack of a functioning

I'm encountering an issue with fetching data from an API. When I try to map through my array of data, I receive an error message stating that 'map is not a function'. I fetched the data on the index page and passed it as props to the CoinLis ...

What is the best way to access a Python API or local data within the Google Visualization DataTable JavaScript library?

I have been tirelessly working for the past two weeks to figure out how to load a local CSV file into google.visualization.DataTable() or use Ajax to call a Python Flask API that I created. My ultimate goal is to dynamically create a Gantt chart. Here&apo ...

Enhancing the readability of modals with Angular Dialog Service

I have been utilizing the Angular Dialog Service to create popup forms on my website. The source code for this service can be accessed here: https://github.com/m-e-conroy/angular-dialog-service/blob/master/README.md However, I am experiencing an issue wit ...

Lighthouse Issue: Facing PWA Challenges with a "Request Blocked by DevTools" Error

For hours now, I've been struggling to make Lighthouse work in Chrome for my initial PWA project. I feel completely lost as nothing seems to be making sense despite the basic code I have included below. The issue arises when I load the page normally ...

Click on the marker to adjust the map's central position

I've successfully created a leaflet map featuring an array of 3 different locations, each marked with a popup window. Now, I'm looking to implement the functionality that will allow the center of the map to change dynamically when a user clicks o ...

What is the most effective way to eliminate just the last underscore in a string by employing the

I am currently facing an issue with table cell editing. I have the following code that removes all underscores (_) from a string if it contains "test_1_". However, my requirement is to only remove the last underscore and have the string appear as "test_1". ...

Using AngularJS variables within JavaScript code

This is my introduction to using AngularJS. The code snippet below displays the desired output: <a href="http://www.example.com/xyz/{{life.animal}}/" target="_blank">Hello </a> Upon clicking, it redirects to: http://www.example.com/xyz/c ...

Store information in an array for a permanent solution, not just a temporary one

When adding entries to a knowledgebase using the following code, I encounter an issue where the entries are only available during the current session. Upon reloading the site, the entries are lost. Can you help me troubleshoot this problem? Here is a snip ...