Having trouble loading the .obj file with three.js

I'm attempting to load an .obj file using three.js, but I keep encountering an error that says "Failed to load resource: the server responded with a status of 404 (Not Found)"

Here is the example link I am trying:

view-source:

The code I am using is as follows:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>three.js webgl - loaders - OBJ loader</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
        <style>
            body {
                font-family: Monospace;
                background-color: #000;
                color: #fff;
                margin: 0px;
                overflow: hidden;
            }
            #info {
                color: #fff;
                position: absolute;
                top: 10px;
                width: 100%;
                text-align: center;
                z-index: 100;
                display:block;
            }
            #info a, .button { color: #f00; font-weight: bold; text-decoration: underline; cursor: pointer }
        </style>
    </head>

<body>
    <div id="info">
    <a href="http://threejs.org" target="_blank">three.js</a> - OBJLoader test
    </div>

    <script src="../build/three.min.js"></script>
    <script src="js/loaders/OBJLoader.js"></script>

    <script src="js/Detector.js"></script>
    <script src="js/libs/stats.min.js"></script>

    <script>

        var container, stats;

        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 loader = new THREE.ImageLoader( manager );
            loader.load( 'textures/UV_Grid_Sm.jpg', function ( image ) {

                texture.image = image;
                texture.needsUpdate = true;

            } );

            // model

            var loader = new THREE.OBJLoader( manager );
            loader.load( 'obj/male02/male02.obj', function ( object ) {

                object.traverse( function ( child ) {

                    if ( child instanceof THREE.Mesh ) {

                        child.material.map = texture;

                    }

                } );

                object.position.y = - 80;
                scene.add( object );

            } );

            //

            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>

</body>

If anyone has successfully implemented the above example, please share how you did it.

Thank you, Pratik

Answer №1

In this particular instance, the problem I encountered involved enabling Mime Type on a Windows Server.

There are two ways to go about it: either manually or through code.

To do it manually:

  1. Navigate to the IIS settings
  2. Access the Mime Type settings
  3. Click on Add
  4. Enter the Mime type extension as .obj
  5. Specify the Mime type as application/octet-stream
  6. Click on Add
  7. Restart your Site or application Pool

If you prefer using code, insert the following into your Web.config file:

<system.webServer>
    <staticContent>
        <mimeMap fileExtension=".obj" mimeType="application/octet-stream" /> 
    </staticContent>    
</system.webServer>

Answer №2

Encountering a 404 error signifies that the specified file cannot be located in the designated location. For instance, if you are working on localhost, make sure that within the same folder as your demo.html file, you have:

  • A folder named obj which contains another folder named male02 that holds a file named male02.obj
  • A folder named textures with a file named UV_Grid_Sm.jpg

The occurrence of this error usually indicates that these directories and files are missing.

If you are an experienced developer, resolving this issue should pose no difficulty. However, if you are new to development and struggling to comprehend where your links lead to, consider dedicating some time to review absolute and relative links:

Answer №3

After encountering a problem, I attempted to fix it by adjusting the Mime settings without any luck. Eventually, I discovered that creating a new file from scratch through my web host panel and transferring the .obj and .mtl code into it, then renaming it with the correct suffix, resolved the issue successfully.

Answer №4

Challenge

You're encountering difficulties when attempting to load .OBJ files using the standard methods provided by Three.js.

For more information, visit this link:

Resolution

A crucial point to note is that using new THREE.OBJLoader(); won't work; instead, you should utilize new OBJLoader();

I managed to find the solution by thoroughly exploring and comprehending the content on the official Three.js website.

The method often mistakenly assumed to be for loading .obj files is actually geared towards handling .JSON file types - it goes by the name ObjectLoader();

To effectively load .obj files, you'll need to employ a Three.js Addon known as OBJLoader();

Procedure for obtaining OBJLoader();

import { OBJLoader } from 'three/addons/loaders/OBJLoader.js';

Once the addon has been imported, follow these steps:

const objLoader = new OBJLoader();

objLoader.load('./my-obj-folder/my-obj-file.obj',(passedObj) => {
  scene.add(passedObj);
  executeGenericFunction();
});

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

Enhancing the Efficiency of JavaScript's indexOf Method

I am currently developing a basic search algorithm in JavaScript. var title = "Discovering the Best Book of All Time"; var search1 = "of DiscoverinG boOk Best"; var search2 = "Of TIme best all" var search3 = "Book discovering time" When using indexOf(), ...

How can I define the boundaries for the scrolling of a static background image?

Is there a way to limit how far a fixed background image can scroll down a page? Essentially, is it possible to change the background attachment to static when the bottom of the background image is 10px away from the bottom edge of its div container? In t ...

AngularJS Reload Scenario: A new way to refresh and enhance

My current project involves the development of a mobile app where I am retrieving data from a REST GET call. Everything is running smoothly. However, I would greatly appreciate expert advice on how to seamlessly re-render this data if the user decides to ...

Trouble with escaping characters in Javascript?

My code looks like this: `message.channel.send( const Discord = require('discord.js'); const client = new Discord.Client(); const token = 'your bot token here'; client.on('ready', () => { console.log('I am ready!& ...

Customizing CSS according to specific URLs

I have two different domains - one ending with .nl and the other ending with .be. For instance, domain.nl and domain.be. Both domains share a similar overall style, but I want certain elements to have distinct styling depending on whether it is the .nl o ...

Show a loading icon as the synchronous Ajax request is being sent

Seeking a way to show a spinner while making a synchronous Ajax request to fetch data from the server. Acknowledging that asynchronous mode is preferred, but not permitted in this case. Aware that a sync ajax request can cause browser blocking. An attemp ...

What is the best way to create a fixed footer in Next.js using React?

I'm looking to create a fixed footer that will stay at the bottom of the page if there isn't enough content to fill it. I've been researching ways to achieve this using CSS, but many of the methods don't easily translate to React/Next.j ...

Removing tab panels within a tab container dynamically in asp.net with the help of vb.net

Currently, I am in the process of developing a chat application using asp.net. My goal is to dynamically create tab panels within a tab container for each user accessing the system. Whenever a new user is selected, a corresponding tab with two text boxes ...

How can I efficiently fetch data from Firebase, manipulate it through computations, and present it using React Hooks?

I am currently working on retrieving multiple "game" objects from Firebase Storage, performing statistical calculations on them, and then presenting the game statistics in a table. Here is an overview of my code structure: function calculateTeamStatistics( ...

What is the method to check for the absence of an anchor element in jest and react-testing-library?

In my React component, a link is rendered based on a specific rule. The markup looks like this when there is a link within the h4 element: <h4><a href="">foo</a></h4> <p>blah blah <a href="">bar</ ...

What is the proper way to terminate a NamedPipeClientStream?

I am facing an issue with my WPF application where the NamedPipeClientStream is continuously running, preventing the application from closing. I have tried using ConnectAsync and disposing the stream, but the process still won't end. The pipe is used ...

What is the best way to generate an image from HTML code?

When I send emails with the HTML created, the design changes when viewed in Outlook. To address this issue, I am attempting to convert the HTML source into an image before sending the email. To do this, I have stored the HTML source in a string variable l ...

Is there an interface designed to integrate 4 different interfaces seamlessly?

Currently, I am working on a sizeable database application and aiming to implement the repository pattern. Within this project, I am utilizing 4 different interfaces: IProductRepository, IFileRepository .... , and I am considering creating a combined inte ...

The onclick event for the asp:button does not trigger, causing the page to simply reload

My ASPX code for the button is shown below: <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> The function for the onclick event in the codebehind file is as follows: public void Button1_Click(object sender, EventArg ...

Identifying web browsers using C# in the .Net framework

Today, I find myself working with C# code. I am currently attempting to create a function that can take in a user agent string and provide me with information regarding the browser name and version. I initially tried using this solution, but encountered is ...

"Uncovering the dangers of XMLHttpRequest: How automatic web-page refresh can lead

Hello, I have been developing a web interface for some hardware that utilizes an 8-bit microcontroller. The webpage includes HTML, JavaScript, JSON, and XHR (XMLHttpRequest) for communication purposes. My goal is to create a page that updates every 250 ...

Instructions for implementing this script in HTML and JavaScript: utilize the clone() function

I came across this code snippet here function displaytickets(){ var $panel = $('<div/>').addClass('col-xs-3 panel panel-default') $panel.append($('<div><h3 class="panel-title">Title</h3></div>&a ...

Vue.js view fails to refresh upon receiving an event through eventbus

Just diving into Vue.js 2 and working on my very first (vue) web application. The setup includes two components - a header component and a login component. Once the login process is successful, a "loggedIn" flag gets toggled within an authentication servic ...

Accessing a function located in a separate file

I am currently developing a Discord bot and I'm looking to define a function in another file to make my code more organized. I have two files: function.js const needle = require("needle"); async function fetch() { const res = await needle("get", ...

The React render function fails to display the components it is supposed to render

Upon running npm start, the browser opens localhost:3000 but only displays a white page. To troubleshoot, I added a paragraph within the <body> tag in index.html. Surprisingly, the text Hello World! appeared for less than a second before disappearing ...