Problem with Loading OBJ Files in THREE.JS

I'm having difficulties with the OBJ Loader in THREE.JS.
Here is the code I've written:

   //Setting up the scene
scene = new THREE.Scene();

//Creating the camera
camera = new THREE.PerspectiveCamera(60, window.innerWidth/window.innerHeight, 1, 1000);

//Setting up the renderer
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth-5, window.innerHeight-5);
document.getElementById('container').appendChild(renderer.domElement);

//Using the loader to load an OBJ file
loader = new THREE.OBJLoader();
loader.load('../disk.obj', function(object){
   scene.add(object);
});

//The main rendering loop
function init() {
   renderer.render(camera, scene);
}

Could you provide some assistance with this issue?

Answer №1

Make sure to include the necessary JavaScript files and call the init method in your code. Also, ensure that the document is fully loaded using window.onload. If your scene appears black, check if you have added lights and included the OBJLoader from the examples folder.

Your HTML structure should look like this:

<!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">
  </head>
  <body>
    <script src="three.js/build/three.min.js"></script>
    <script src="three.js/examples/js/loaders/OBJLoader.js"></script>
    <script src="main.js"></script>
    <div id="container"></div>
  </body>
</html>

In your JavaScript file (main.js), use the following template:

window.onload=function(){
  init();
  animate();
}

function init() {

  container = document.getElementById( 'container' );
  console.log(container)
  camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
  camera.position.z = 100;

  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 );

  var loader = new THREE.OBJLoader();
  loader.load( 'three.js/examples/obj/male02/male02.obj', function ( object ) {
    console.log(object);
    scene.add( object );
  } );

  renderer = new THREE.WebGLRenderer();
  renderer.setSize( window.innerWidth, window.innerHeight );
  container.appendChild( renderer.domElement );

}

function animate() {

  requestAnimationFrame( animate );
  render();

}

function render() {

  renderer.render( scene, camera );

}

Answer №2

When executing your load function, consider implementing the following in your callback:

loader.load('', function( geometry ){
    mesh = new THREE.Mesh( geometry, customMaterial);
    scene.addObject(mesh);
});

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

Tips for saving images in an S3 bucket

Within my express application, I currently save images to a directory in my repository. However, I am beginning to think that this approach may not be ideal and I am considering using AWS S3 as an alternative storage solution. Since I have never worked w ...

"Communication breakdown in Vue.js: $emit event not being picked up by corresponding $

Vue.component('rating-edit', { template:` <form> <input v-model="rating.title" type="text"> <textarea v-model="rating.remark">{{rating.remark}}</textarea> <button type="button" @click=" ...

Submitting several individual files through distinct Dropzones within a single form

I have implemented a form that allows users to add multiple rows, each containing name and avatar fields. My goal is to utilize Dropzone.js in order to create individual droppable areas for each avatar field. Every time a new row is added, a new Dropzone ...

Utilizing Filepond to extract base64 data in a React JS environment

Struggling to extract a base64 from an image upload and send it along with other values to the server. Due to API limitations allowing only 2 files at a time, I'm unable to process uploads individually. Having difficulty in mapping the 'data&apo ...

Guide on how to showcase an array in a string format using table rows in JavaScript or jQuery

After making an AJAX call to a PHP database, I receive a String as a result in my script. The format of the string is shown below: array(4) { [0]=> array(3) { ["id"]=> string(3) "181" ["number"]=> ...

What is the best way to link my React application with my Express API?

I've been immersed in my react app project for a while now, and I've recently delved into developing a server (using node and express) as well as planning to incorporate a database for it (MongoDB). My client-side react app has been smoothly run ...

Adjusting an image size using JQuery after resizing a canvas will only resize the image itself, not

How can I resize an image within a canvas using JQuery in a way that only the image is resized, not the entire canvas? function resizeImage(width, height){ var image = document.getElementById('resizeImage'), canvas = document.createEleme ...

How to retrieve a string value from an object in Express.Js by using the key value pair

I'm wondering about the proper way to retrieve a value from an object where the key value is a string. This involves sending data from the client side and receiving it on the backend using express.js. Example of data sent from the client side: var ...

"Transferring an array of data to a Laravel controller via AJAX: A step-by-step guide

Is there a way to send arrays of data to the back-end all at once? The Problem 1. This is what I'm currently sending: array:5 [ "_token" => "S5s5ZTTnnP93MyXgCql0l9vhHsiqt5VWaFyEedXj" "product_id" => "21" "specification_id" => "6" " ...

Display one of two divs after clicking a button depending on the input from a form field

My apologies for my limited knowledge in JavaScript and jQuery. I'm attempting to show one of two divs based on input from a form. Specifically, there's a button next to a form field that asks users to enter their zip code to check if they are wi ...

The drop-down menu remains visible even after clicking outside of it

I've written a script that works when clicked, but it doesn't hide when clicked outside of it. $(document).ready(function() { //Translate(); //caling Language Translater function $("#translate_image").attr('href', base_url) ...

Equivalent of ResolveUrl for loading scripts without the need for server technology

I am in the process of converting an ASP.NET web page into a plain HTML web page. Most of the work is done, however, I am having trouble replacing the ASP.NET Page.ResolveUrl function when setting a reference to a javascript file: <script src="<%= ...

Adjusting the alignment of the horizontal bars in react-chartjs-2

I have configured the graph with the following settings: { type: 'horizontalBar', indexAxis: 'y', barThickness: 12, scales: { x: { suggestedMax: 6, suggestedMin: 0, grid: { display ...

During the click event, two distinct $.ajax requests interfere and cancel each other out

Here's a dilemma I'm facing: On my webpage, I have implemented two different click events. The first one opens a modal displaying a larger image when you click on a thumbnail picture (similar to Instagram on PC - I created an Instagram clone for ...

Troubles encountered with adapting apexcharts size within a react environment

As a novice front-end coder transitioning from a data analyst background, I am currently facing an issue with integrating an ApexChart visual into a flexbox element. The visual appears fine at a resolution of 2560x1440 pixels. However, upon further resizin ...

Getting access to the properties of an array containing objects

Check out the data below: [ { "name": "Fluffy", "species" : "rabbit", "foods": { "likes": ["carrots", "lettuce"], "dislikes": ["seeds", "celery"] } }, { "name": "Woofster", "species" : "dog", "foods": { ...

retrieving data from array elements

{ "success": true, "users": [ { "photo": { "id": "users/m1ul7palf4iqelyfhvyv", "secure_url": "https://res.cloudinary.com/dpbdw6lxh/image/upload/v1665251810 ...

Guide to refreshing a localStorage variable before transferring it to an Ajax request

I have a scenario where I need to update the localStorage value when an option is clicked from a list. The data-id value of the clicked option should be stored in localStorage and then sent through an Ajax call. However, the issue I am facing is that the l ...

Utilizing data from an external JavaScript file in an Express application

I am currently developing an application using Node.js Express, where I need to pass some data from Express and utilize it in an external JavaScript file. Below is my app.js: const express=require('express'); const path=require('path&apos ...

Managing Subdomains in Nuxt.js Using Vue.js

I am currently developing a Nuxt.js (vue.js) application. I am aware that Nuxt automatically generates routes based on the directory structure within the 'pages' folder. I am curious about how it would handle subdomains. My goal is to establish ...