Exploring the Mystery of why Three.js Fails to Apply Textures to Objects

I'm attempting to add a texture to an object with the following code:

    <html>
    <head>
        <title>My first Three.js app</title>
        <style>
            body { margin: 0; }
            canvas { width: 100%; height: 100% }
        </style>
    </head>
    <body>
        <script src="three.min.js"></script>
        <script src="OBJLoader.js"></script>        
<script>
           var container;
            var camera, scene, renderer;
            var mouseX = 0, mouseY = 0;
            var windowHalfX = window.innerWidth / 2;
            var windowHalfY = window.innerHeight / 2;
            init();
            animate();
            function init() {
                container = document.createElement( 'div' );
                document.body.appendChild( container );
                camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
                camera.position.z = 100;
                // scene
                scene = new THREE.Scene();
                var ambient = new THREE.AmbientLight( 0x101030 );
                scene.add( ambient );
                var directionalLight = new THREE.DirectionalLight( 0xffeedd );
                directionalLight.position.set( 0, 0, 1 );
                scene.add( directionalLight );
                // texture
                var manager = new THREE.LoadingManager();
                manager.onProgress = function ( item, loaded, total ) {
                    console.log( item, loaded, total );
                };
                var texture = new THREE.Texture();
                var onProgress = function ( xhr ) {
                    if ( xhr.lengthComputable ) {
                        var percentComplete = xhr.loaded / xhr.total * 100;
                        console.log( Math.round(percentComplete, 2) + '% downloaded' );
                    }
                };
                var onError = function ( xhr ) {
                };
                var loader = new THREE.ImageLoader( manager );
                loader.load( 'bb.jpg', function ( image ) {
                    texture.image = image;
                    texture.needsUpdate = true;
                } );
                // model
                var objLoader = new THREE.OBJLoader( manager );
                objLoader.load( 'note4.obj', function ( object ) {
                    object.traverse( function ( child ) {
                        if ( child instanceof THREE.Mesh ) {
                            child.material.map = texture;
                        }
                    } );
                    object.position.y = - 80;
                    scene.add( object );
                }, onProgress, onError );
                //
                renderer = new THREE.WebGLRenderer();
                renderer.setSize( window.innerWidth, window.innerHeight );
                container.appendChild( renderer.domElement );
                document.addEventListener( 'mousemove', onDocumentMouseMove, false );
                //
                window.addEventListener( 'resize', onWindowResize, false );
            }
            function onWindowResize() {
                windowHalfX = window.innerWidth / 2;
                windowHalfY = window.innerHeight / 2;
                camera.aspect = window.innerWidth / window.innerHeight;
                camera.updateProjectionMatrix();
                renderer.setSize( window.innerWidth, window.innerHeight );
            }
            function onDocumentMouseMove( event ) {
                mouseX = ( event.clientX - windowHalfX ) / 2;
                mouseY = ( event.clientY - windowHalfY ) / 2;
            }
            //
            function animate() {
                requestAnimationFrame( animate );
                render();
            }
            function render() {
                camera.position.x += ( mouseX - camera.position.x ) * .05;
                camera.position.y += ( - mouseY - camera.position.y ) * .05;
                camera.lookAt( scene.position );
                renderer.render( scene, camera );
            }
        </script>
        <div><canvas width="1360" height="150" style="width: 1360px; height: 150px;"></canvas></div>
    </body>
</html>

All the js files, texture, and object file are located in the same folder. When I open the page, I encounter errors, particularly in Firefox which displays the following messages:

    THREE.WebGLRenderer 69
THREE.WebGLRenderer: OES_texture_float extension not supported.
THREE.WebGLRenderer: OES_texture_float_linear extension not supported.
THREE.WebGLRenderer: OES_standard_derivatives extension not supported.
requestAnimationFrame is not defined
[Break On This Error] requestAnimationFrame( animate );
index.html (line 83)
bb.jpg 1 2
text is undefined
[Break On This Error] var lines = text.split( '\n' );
OBJLoader.js (line 195)

I'm seeking assistance in identifying what I may be doing wrong. Looking forward to your feedback.

Answer №1

When it comes to loading textures, there are different methods to consider:

var loader = new THREE.ImageLoader( manager );
    loader.load( 'bb.jpg', function ( image ) {
        texture.image = image;
        texture.needsUpdate = true;
} );

In most examples, textures are loaded using a different approach, such as:

var texture = THREE.ImageUtils.loadTexture('path/to/texture.png');

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

Transfer information from a Vue function to an external JSON document

I would like to store the data for my Vue project in an external JSON file instead of within the Vue function itself. I attempted to retrieve data from an external file using the code below, but encountered issues, possibly due to a conflict with the "ite ...

Cannot locate AngularJS + Typescript controller

I'm encountering an error while attempting to integrate TypeScript with AngularJS. The issue I'm facing is: Error: [$controller:ctrlreg] The controller named 'MyController' has not been registered Does anyone have any insights on what ...

Create a dynamic dropbox using JavaScript/JQuery in an HTML page

I am currently working on implementing 3 different drop down boxes that are triggered by 4 different buttons. These drop down boxes should appear within the #apple div. When Button B1 is clicked, the drop down options include Apple, Mango, and Papaya. Whe ...

Properly Adding an External jQuery File in HTML Using jQuery

Seeking assistance as a newcomer to JS and programming in general. Currently working on a website where each page has its own HTML / PHP file, with jQuery and global JS functions included in the footer via a separate includes file "footer.php". Everything ...

Monitor user activity for when they click the back button in their browser

Is there a way to detect when the user clicks on the back button of the browser? I'm working on an Ajax application and being able to detect back button clicks would allow me to display the appropriate data. I am open to solutions in PHP, JavaScript ...

Risk Score Generating Form

As I work on a comprehensive form, there are 5 sections for users to mark if they qualify (using checkmarks). The form consists of approximately 50 questions in total. Each section carries different weights/points (e.g., Section 1 is worth 1 point each, ...

The functionality of the .toggle method is limited to only being effective 1.5

I'm having an issue with making an image popup using the .toggle function in javascript. It seems to work initially, but then only works partially after that. When I click on the image, it opens as expected. However, when I try to close it by clickin ...

Tips for positioning HTML elements at the exact mouse location as it moves, without any delay?

Currently, I am in the process of developing a web-based drawing application that does not rely on using a canvas. My decision to avoid using a canvas is because I plan to incorporate CSS Keyframes into the HTML elements upon placement. This approach allow ...

When onSubmit is triggered, FormData is accessible. But when trying to pass it to the server action, it sometimes ends up as null

I am currently utilizing NextJS version 14 along with Supabase. Within my codebase, I have a reusable component that I frequently utilize: import { useState } from 'react'; interface MyInputProps { label: string; name: string; value: stri ...

The Angular carousel fails to display or operate properly

I am encountering an issue where the content is not displaying when using the angular-carousel directives: <ul rn-carousel rn-carousel-controls rn-carousel-index="carouselIndex" rn-carousel-buffered > <li ng-repeat="slide in slides track by ...

Triggering a Bootstrap 5 dropdown through code is only effective within the browser's developer console, rather than standard JavaScript implementation

I attempted to display a Bootstrap5 dropdown by clicking on a link in my web application. Despite trying various methods, such as dispatching events and utilizing the bootstrap Dropdown classes, I was unable to achieve success. Interestingly, both approach ...

What could be causing this error to occur when running my React app and clicking the submit button on the form?

CodeBlock.js import React from "react"; import { useState } from "react"; import axios from 'axios' const CodeBlock=()=>{ const [formData, setFormData]=useState({name:'', password:''}); const hand ...

The DELETE function in express.js with MySQL integration is encountering a problem where it is unable to

As I work on setting up my website, the backend utilizes express.js to send queries to a MySQL Database. However, when attempting to delete rows, no action seems to take place. function establishConnection() { return mysql.createConnection({ multipl ...

Received an error during the module.exports = client process

In my commands folder, I have multiple files that contain slash commands. I am trying to import the client instance from index.js to another file, but when I use module.exports = client;, it ends up executing the entire index.js script unintentionally. I ...

When a Javascript function marked as async is executed, it will return an object

Async function is returning [object Promise] instead of the desired real value. Interestingly, I can see the value in the console log. It seems like this behavior is expected from the function, but I'm unsure how to fix my code. This code snippet is ...

I have a website hosted on Heroku and I am looking to add a blog feature to it. I initially experimented with Butter CMS, but I found it to be too pricey for my budget. Any suggestions on

I currently have a website running on Heroku with React on the front end and Node.Js on the back end. I want to incorporate a blog into the site, but after exploring ButterCMS, I found the pricing starting at $49 to be too steep for my budget. My goal is ...

Efficiently organizing reducers into separate files in ReactJS and merging them together

My App is a simple counter app where buttons are images with their own counters. https://i.stack.imgur.com/qkjoi.png In my App.js file, I imported the reducer for the counters using the following code: import reducer from './reducers/reducerCounter&a ...

Is there a way to eliminate unnecessary chunks from MUI in NextJS?

https://i.sstatic.net/zAkV0.png I recently created a single page and noticed that there is a significant amount of unused JavaScript in my codebase. Specifically, I am using MUI and React icons. Any suggestions on how to efficiently manage this issue? T ...

When attempting to access a static method in TypeScript, an error occurs indicating that the property 'users_index' does not exist on the type 'typeof UserApiController'

Just dipping my toes into TypeScript and attempting to invoke a function on a class. In file A: import userAPIController from "./controllers/customer/userAPIController"; userAPIController.users_index(); In file B: export default class UserApiControlle ...

methods for transforming JSON array output objects into individual non-array values

I'm facing an issue with a JSON result that contains latitude and longitude as an array like [13.0801721, 80.2838331]. I need help in converting this to comma-separated values without the array brackets, similar to 13.0801721, 80.2838331. This is my ...