I am facing issues with loading my Obj file when attempting to provide the file path from the project directory

import * as THREE from 'three';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';

// Setting up the scene, camera, and renderer
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(65, window.innerWidth / window.innerHeight, 0.1, 800);
camera.position.z = 5;
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// Adding lighting to the scene
const ambientLight = new THREE.AmbientLight(0x404040); // Soft white light
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(0, 1, 0); // Adjust position if needed
scene.add(directionalLight);

// Initializing the OBJLoader
const loader = new OBJLoader();

// Loading the .obj file into the scene
loader.load(
    '../src/assets/models/test.obj', // Check the path is correct!
    function (object) {
        scene.add(object);
        console.log('Successfully loaded OBJ file.');

        object.position.set(0, 0, 0);
        object.scale.set(0.01, 0.01, 0.01);
        camera.lookAt(object.position);

        // Modifying materials of the object
        object.traverse(function(child) {
            if (child instanceof THREE.Mesh) {
                child.material = new THREE.MeshBasicMaterial({ wireframe: true });
                child.material.side = THREE.DoubleSide; // making it double-sided
            }
        });

        animate(); // Starting the animation loop after loading the model
    },
    function (xhr) { // Optional: Progress callback
        console.log((xhr.loaded / xhr.total * 100) + '% loaded');
    },
    function (error) { // Error callback
        console.error('An error occurred:', error);
    }
);

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

I'm having difficulty importing the obj file into my viewer, possibly due to an issue with the file path within the project folder.

The screen appears black when I try to render the model.

Any suggestions on how to resolve this?

Answer №1

Your item has been successfully loaded. Consider adjusting the scale for better visibility. My intuition suggests it may have a red hue... Check the scale:

object.scale.set(0.01, 0.01, 0.01);

Enlarge it

object.scale.set(2, 2, 2);

https://i.sstatic.net/fQkug.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

typescriptCreating a custom useFetch hook with TypeScript and Axios

I have a query regarding the utilization of the useFetch hook with TypeScript and Axios. I came across an example of the useFetch hook in JavaScript, but I need help adapting it for TypeScript. The JavaScript implementation only handles response and error ...

Tips for preserving a data point within a ReactJS layout and transferring it to different pages

Just a heads-up, I'm new to ReactJS and still learning the ropes. Here's the back-end code for the login page written in nodejs: app.post("/login", (req, res) => { const { username, pass } = req.body; sqlLoginuser = "SELECT * FROM use ...

A guide on scheduling automatic data insertion in mongoose.js

I'm working on a website with Node.js and Mongoose, and I could use some guidance on how to automatically insert data into Mongoose with Node.js at specific times. For example, at the end of each month, I want my current data to be stored in the Mongo ...

Can JSON values be multiplied together?

Can you assign the value of a key in JSON by using the result of multiplying/adding two variables, values, strings+number, or strings+strings? Is this feasible? For example: { "string": "600*"+40 } ...

Newbie in Web Development: What is the best way to transfer a complicated object between different PHP files?

As a native application developer primarily working with C++, I have unexpectedly found myself involved in a small business coding project for a friend. While I am accustomed to self-contained native applications, I am facing a challenge on this new projec ...

"The seamless integration of Ubergallery with AJAX functionality creates a

When I attempted to access the Ubergallery through an Ajax call, I encountered numerous issues that I was able to resolve using the script provided below. However, despite resolving most of the problems, I am now facing a new issue - the navigation buttons ...

Chose to conceal all child elements, but is unable to reveal all elements when clicked

Currently, I am in the process of creating a jQuery accordion by following the tutorial provided on css-tricks at this link. After making some modifications to the code, I was able to hide all the elements within the parent element. However, upon clicking, ...

Updating state in Vue by utilizing an array of item values

Hello everyone In a simple application, I am attempting to visualize the insertion sort algorithm using Vue. I have successfully written a function that sorts a list of items and returns an array showing each step of the sorting process. The final array i ...

XMLHttpRequest Failing to Retrieve Data - Error Code 202

Currently, I am immersed in a project that involves using a webservice (specifically, VB.Net and Javascript). While debugging the code, I encountered an issue with the XmlHttpRequest.status returning as 202. Upon comparison with my previous webservice proj ...

404 error occurs when routing in Express.js is unable to find the

Seeking Assistance I am encountering an issue with my express.post() routing as it returns a 404 state. Current Implementation The code in my server.js file seems fine, but I am facing this routing problem. // Required modules and database connection v ...

Tips for implementing csurf in Express 4.0

I have looked into the csurf module's wiki, but unfortunately, it appears to be blank. This particular module enhances user requests by including a csrfToken() function, however, I am unsure of how to properly utilize it. Could someone kindly provide ...

How does jQuery create a hover effect that changes the background color of a link and keeps it when the mouse hovers over a

I'm attempting to add a background color to the main link that displays a sub-menu. Currently, only the sub-menu is visible, and as soon as the mouse moves away from the main link, the color reverts back to the original background color. <nav& ...

Remove the session variable when a JavaScript function is triggered

After creating a function called destroy(), I have set it to be called on the onclick event of the logout button. However, the issue is that the server-side code within that function is always executed when the page loads, regardless of whether the logou ...

Utilizing getUserMedia to capture portrait shots with the back camera

I am encountering an issue with starting the back camera in portrait mode using navigator.mediaDevices.getUserMedia in React. The camera does not appear to be taking into account the constraints I have set. Below is how the code looks for initialization: ...

Display the title when the mouse hovers over

I am currently working on a minimalist portfolio site where I showcase various projects through images on the landing page. As I iterate over all the projects using {projects.map(({ id, title, route, src }, index) => ())}, I encountered an issue with di ...

Using Typeof in an IF statement is successful, but attempting to use ELSE with the same

My goal is to create a JavaScript variable called str. In case the ID idofnet doesn't exist, I would like to prompt the user for a value to assign to str. However, if idofnet does exist, then I want to retrieve its value and assign it to str. This is ...

Custom classes and interfaces are failing to be recognized by Typescript

I am facing a strange issue where my custom types are not being recognized by my AngularJS controller. I have made sure that all files have full write permissions. Instead of using a tsconfig.json file, I rely on Visual Studio 2019 which has TypeScript su ...

Is there a way to extract information from an external XML document and incorporate it into an HTML file?

I am attempting to extract information from an XML file that is not stored on my website's server. My goal is to utilize this data for various purposes, such as generating charts. One specific example involves using weather data from an XML file locat ...

kineticjs equivalent to jquery sortable

Could someone recommend a kineticjs plugin or script that works with jquery's "sortable" function? I am trying to create a list of shapes where I can drag and drop them, and when one element moves, the other elements shift into place. ...

Parsing Problem---Is there a Parsing Error?

My code includes a function that calculates the total of cells and then displays it in a textbox: function UpdateTotal() { var total = parseFloat('0.0'); $("#<%= gvParts.ClientID %>").find("tr").not(".tblResultsHeader").each(funct ...