Load various file formats into a Three.js scene

I am working on a project where I need to create a function that can load a 3D object into ThreeJS. The user will upload the file onto our website, and it could be in various formats such as STL, JSON, Babylon, Collada, etc.

Currently, my code only supports loading one specific format, which is shown below:

// BEGIN Clara.io JSON loader code
var objectLoader = new THREE.ObjectLoader();
objectLoader.load('clara.json', function(obj) {
    object = new THREE.Mesh(obj);
    scene.add(object);
});

Is there a way in ThreeJS or any other method available that can automatically load the 3D object into the scene based on the uploaded file format?

Answer №1

If you're looking to enhance your skills, I recommend checking out the source code for the three.js editor. It's important to ensure that you have all the necessary loaders included and create a comprehensive switch statement to select the appropriate loader based on the file extension.

https://i.sstatic.net/someUniqueLink.png

Answer №2

To determine the appropriate loader, it is best to utilize the file string -

Consider using a function like this:

loadArbitraryModel("path/to/file.json");

loadArbitraryModel = function(path) {
    var strings = path.split('.'); //now the path is ["path/to/file", "json"]
    var types = ['json', 'obj', 'stl', 'babylon', 'collada'];
    var result = -1;
    types.forEach(function (item,index) {
        if (strings.length > 1) {
            if (strings[1] == item){ //strings[1] represents anything after the '.'
                result = index;
            }
        }
    });
    switch (result){
        case -1:
            alert("file format not supported/ improperly named");
        case 0:
            loadJSON(path);
            break;
        case 1:
            loadOBJ(path);
            break;
        case 3:
            loadSTL(path);
            break;
            //ETC etc etc
    }
}

An alternative approach is to define loadXXX multiple times for each file type. Alternatively, consider a load(loader,path) function where you specify which loader to use. For instance, in the json case ->

load(new THREE.ObjectLoader(),path)
. The loaders typically have similar functionalities within the function load( __, __), eliminating redundant code across functions.

This method does not accommodate errors from incorrectly labeled extensions. However, you can address this by defining an onError function within the loadXXX() function to generate an alert if the loader encounters parsing issues.

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

Extract form input to utilize in nodemailer

Currently I am working on a form implementation where I intend to utilize nodemailer for sending test emails to myself. My goal is to have the email inputted into the form dynamically appear in both the "to" and "subject" fields when the user submits the f ...

Using MIPS Assembly Language: Displaying Register Content on Screen

I'm working on replicating a simple form of debugging in MIPS similar to javascript. I am wondering how I can achieve the equivalent of this ($t0 represents a javascript variable here): console.log($t0); In simpler terms, I am looking for the metho ...

What is the best way to extract the text from a class only when it is nested within a particular header tag?

const request = require ('request'); const cheerio = require('cheerio'); const fs = require ('fs'); request("http://kathmandupost.ekantipur.com/news/2018-08-31/bimstec-summit-multilateral-meet-underway.html", (error, response ...

tag containing inner text of span tag tagged with anchor tag

Using JavaScript, I have dynamically assigned an anchor tag within a span tag. However, the href attribute of the anchor tag is being formed incorrectly. Here is the JavaScript code: var HF1Id , HF2Id , SpanId , HF1Id = '<%=Request("HF1Id") %> ...

Tips for validating a form in AngularJs when utilizing the ng-repeat directive

Within my AngularJS form, I successfully implemented validation for an email field. However, upon adding another email field, the validation applies to all items. My intention is for only the first field to be validated as required. <form novalidate na ...

An engaging webpage with a dynamic scroll feature

I recently inherited a dynamic HTML page that utilizes bootstrap and jqxGrid, and it calls server side code to retrieve data. However, after the data is loaded and the jqxGrid is populated, the page automatically scrolls down. Since I got the code from a ...

Having difficulty displaying elements from two arrays at particular intervals

I am currently working with two arrays that have the same number of items in each. My goal is to print these items in intervals within the console. The desired output would look something like this: 1 Bruce Wayne 45 Then, after a one-second interval, it s ...

Header Express does not contain any cookies, which may vary based on the specific path

In my express.js app, I have two controllers set up for handling requests: /auth and /posts. I've implemented token authorization to set the Authorization cookie, but I'm encountering an issue when making a request to /posts. The request goes th ...

Three.js - creating stunning 3D visuals that seamlessly blend with 2D images

I am currently working on a project in three.js that involves creating a movable 3D-view on top of a static 2D-rectangle image. While everything is functioning properly, I am facing an issue where the buildings at the upper edge are not visually aligned co ...

Can you explain the contrast between using require('d3') and require('d3-selection')?

While working on a nodejs application with javascript, I encountered an interesting issue. In my code, I am passing a d3 selection to a function as shown below. // mymodule.js exports.myfunc = function(ele){ if(ele instanceof d3.selection){ // do so ...

When you attempt to upload an MP3 file to a NodeJS Express server, the file becomes

I am facing an issue with uploading an MP3 file from my web client to a Node Express server. The uploaded file gets corrupted and I am unable to play the song using an MP3 player after writing it to disk. The problem seems to occur when uploading the file ...

Unable to send a post request using ajax

Section of Form in home.php <div id='googleForm'> <form> <div class='item'> <label class='label'>Full Name</label> <input class=&apos ...

The issue of the marker vanishing upon refreshing the page on AngularJS

Currently, I am encountering a rather peculiar issue. Upon the initial page load, the code snippet below correctly displays a marker at the specified coordinates and ensures the map is properly centered: <div class="paddingtop"> <map data-ng- ...

What steps do I need to take to integrate Twilio's SMS service into an HTML document?

I have been searching for solutions using php and node.js (which is a derivative of js, so it should work), but I came across this library: <script type="text/javascript" src="//media.twiliocdn.com/sdk/js/client/v1.4/twilio.min.js"></script> ...

The issue with mapDispathToProps is that it is failing to assign a function

import React, { Component } from "react"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import { ShelfModal } from "./shelf-modal"; import { openShelfModal } from "../../../redux/actions/shelf-modal"; export class ShelfTest ex ...

Tips for setting the id parameter on the asp-route-id for the modal button

My code is causing me some trouble. I have a table with 3 columns: category, subcategories and actions. In the third column, I display buttons "Edit" and "Delete". Here is a snippet of my code: <tbody> @foreach (var category in Model.ToList() ...

transformation of an array into a string in JavaScript

I am working with a javascript array that contains different elements: [div.parts, div.editor, div.inside-1, div.container-2, div.inside-wrapper, div#content, div.whitebgpan, div, div#maindiv, body, html] My goal is to convert this array into a string wi ...

Troubleshooting jsPDF problem with multi-page content in React and HTML: Converting HTML to PDF

I need to convert HTML content in my React application into a PDF file. My current approach involves taking an HTML container and executing the following code snippet: await htmlToImage .toPng(node) .then((dataUrl) => { ...

Retrieve the values of two datepicker components when onChange event occurs in ReactJS

I'm trying to use the DatePicker component from materialui to create a date range using two DatePicker components within one function. Currently, I have a handleChange function that successfully retrieves the value of a single DatePicker component bu ...

What strategies can be employed to combine Material-UI Autocomplete and react-virtualized?

Currently, in one of my projects, I am incorporating the Autocomplete component from Material-UI. Given the large number of options to display, implementing virtualization would prove to be highly advantageous. Initially, I referred to the virtualized exam ...