Reading a glTF file from the local system onto Javascript's memory

Currently, I am working on developing a native iOS and Android application using three.js and Capacitor. One of the challenges I am facing is loading GLTF models from an asset folder that is bundled with the code and delivered to the user. I am unsure about the best approach to tackle this issue.

The documentation for the GLTF Loader's load function can be found here. It requires a URL to load the model. On the other hand, the Parse function takes a "glTF asset to parse, as an ArrayBuffer". How can I effectively load this glTF file into memory while adhering to best practices? I attempted to use

import * as Model from './models/myModel.gltf'
, but encountered a Cannot find module error.

Answer №1

My approach to loading a gltf file involves utilizing a method called reader to load any file within the scene, followed by parsing it using loader.parse. However, if you simply require a folder of sample models, there may be no need for the reader method and parser. You can simply use the basic load GLTF method and store your samples in an array or object. I hope this information proves helpful to you.

loadGltf(file, filename) {
        reader.onload = readerEvent => {
            const contents = readerEvent.target.result;
            const loader = new THREE.GLTFLoader()
            try {
                loader.parse(contents, '', function (gltf) {
                    gltf.scene.traverse(function(child) {
                        if (child.isMesh) {
                            child.castShadow = true;
                            child.receiveShadow = true;
                        }
                    });
                    currentModel = gltf.scene;
                    scene.add(gltf.scene);
                });
            }
            catch(error) {
                alert("Your file " + Load.filename + " was not parsed correctly." + "\n\n" + "ERROR MESSAGE : " + error.message);
            }
        }
        reader.readAsArrayBuffer(file);
    }

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

Explore the next page on the API response by navigating to another page

In my next app, I have a versatile function called postAPI, which is used to send requests to the backend server. import Router from 'next/router'; export const postAPI = async ( endpoint, data = {}, headers = {}, method = 'POST&apos ...

Steps for inserting an item into a div container

I've been attempting to create a website that randomly selects elements from input fields. Since I don't have a set number of inputs, I wanted to include a button that could generate inputs automatically. However, I am encountering an issue where ...

Error encountered with the {1}+ possessive quantifier in a JavaScript regex pattern

As I delve into learning Javascript and Express.js simultaneously, I decided to experiment with regular expressions while making a get request. To familiarize myself with regular expressions, I referred to this chart (also shown below). Greedy Reluctant ...

The compilation of the Angular application is successful, however, errors are arising stating that the property does not exist with the 'ng build --prod' command

When compiling the Angular app, it is successful but encountered errors in 'ng build --prod' ERROR in src\app\header\header.component.html(31,124): : Property 'searchText' does not exist on type 'HeaderComponent&apo ...

Unnecessary socket.io connection in a React component

Incorporating socket.io-client into my react component has been a learning experience. Most tutorials recommend setting it up like this: import openSocket from 'socket.io-client'; const socket = openSocket('http://localhost:8000'); In ...

Start by executing the function and then proceed to upload a static file

Here is the code I am working with: var express = require('express'), app = express(); app.use(express.static(__dirname + '/static')); app.get('/', function(req, res) { //??? }); app.listen(80); I need to first ex ...

What is the best way to share an array from a component to App.js in React?

I've been experimenting with using an array of "components" in my App.js file, where the array is initially set in the Sidebar.jsx component. Sidebar.jsx : import ... const Sidebar = () => { ... const apps = [ // name - how it appears on the ...

personalizing material-ui component styles – set select component color to be pure white

I am looking to implement a dropdown menu using material-ui components (refer to https://material-ui.com/components/selects/). To do so, I have extracted the specific component from the example: Component return <div> <FormControl variant="outli ...

Creating a Pyraminx using triangular shapes

Attempting to create a Pyraminx, a tetrahedron made up of multiple triangles, through my coding. The approach I am taking may not be very precise. You can find my code here: https://codepen.io/jeffprod/pen/XWbBZLN. The issue I'm facing is manually in ...

What is the best way to compare two date strings with the format dd/mm/yyyy using JavaScript?

When attempting to compare a "Date" type of data with an "Any" type of data, the comparison is not functioning as expected. The date is retrieved in the following code: var today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); v ...

Running a JavaScript file enclosed within an AJAX response

I have a web application built with HTML5 that utilizes jquery 3.2.1. Within the application, there is a search feature that makes an ajax request. The response from this request includes HTML code, which contains a <script> tag linking to a js file ...

Using numerous textures for a single mesh in THREE.js

I am working with an OBJ file that utilizes four textures. The UV coordinates in the file range from (0, 0) to (2, 2), where (0.5, 0.5) corresponds to a coordinate in the first texture, (0.5, 1.5) is a UV coordinate in the second texture, (1.5, 0.5) repres ...

The amazing magnific popup boasts a pair of close buttons

I recently started working on integrating a front-end HTML theme with a back-end Laravel app. Oddly enough, I noticed that the popup modal is displaying two close x buttons instead of just one. Despite my efforts, I have been unable to pinpoint what exactl ...

Connecting two anchor elements with a straight vertical line

VISUAL REPRESENTATION Is there a way to add a vertical line between two empty elements in HTML without affecting the layout or interrupting the content? The line should be positioned to the left of the text and should span across multiple paragraphs regar ...

Custom mute bot using Discord.js with the ability to specify duration and provide a reason

I'm creating a discord.js mute bot and encountering some issues with its functionality. Is there a way to program it so that when someone types the command !mute User, it automatically sets the time to 30min and the reason as No reason Specified. How ...

I'm curious about the process by which custom hooks retrieve data and the detailed pathway that custom hooks follow

//using Input HOOK I am curious to understand how this custom hook operates. import { useState } from "react"; export default initialValue => { const [value, setValue] = useState(initialValue); return { value, onChange: event =&g ...

Implementing the use of a partial view in ASP.NET MVC with the help of JavaScript

I am faced with a challenge of displaying 15 different partial views based on the user's selection from a menu tab. Essentially, I have these 15 menu tabs on one side of the page, and when a user clicks on a tab, the content related to that tab should ...

Display or conceal columns based on their index

<div ng-controller="checkBoxController"> <div id="myModal" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="moda ...

Tips for testing nested HTTP calls in unit tests

I am currently in the process of unit testing a function that looks like this: async fetchGreatHouseByName(name: string) { const [house] = await this.httpGetHouseByName(name); const currentLord = house.currentLord ? house.currentLord : '957'; ...

Verification cannot be completed with the bootstrap modal

I want to implement the use of a bootstrap modal when submitting form data. However, I do not want the form to be submitted if it is empty. Currently, when I try to trigger the bootstrap modal on submit with an empty form, the modal appears instead of prom ...