Looking to import a 3D gltf model using the input tag in an HTML file for use in three.js (JavaScript), but encountering an issue with the process

I am trying to upload my 3D model from an HTML input tag, but I keep encountering this error message:

t.lastIndexOf is not a function

Here's the HTML code I am using:

<input type="file" id="MODEL" />
<button onclick="GLTFLoader()" id="LOAD" type="submit">Load_model</button>

And this is the JavaScript code I have written for loading the model:

function GLTFLoader() {
    const MODEL = document.getElementById("MODEL").files[0];
    var Mesh;
    let LOADER = new THREE.GLTFLoader();
    LOADER.load(MODEL, (gltf) => {
        Mesh = gltf.scene;
        Mesh.scale.set(0.2, 0.2, 0.2);
        scene.add(Mesh);
        Mesh.position.x = 0;
        Mesh.position.y = 10;
        Mesh.position.z = 15;
    });
}

Answer №1

To capture the change event on the file input and then convert the file blob into a blob URL, you can follow this approach:

const loader = new GLTFLoader();
const input = document.querySelector("input");
input.addEventListener("change", (event) => {
  const file = event.target.files[0];
  const url = URL.createObjectURL(file);
  loader.load(url, (gltf) => {
    scene.add(gltf.scene);
  });
});

Below is a demonstration of how it works:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

canvas {
  display: block;
}

input {
  position: absolute;
  z-index: 1;
  top: 1em;
  left: 1em;
}
<input type="file" />

<script type="module">
  import * as THREE from "https://cdn.jsdelivr.net/npm/three@latest/build/three.module.js";
  import { OrbitControls } from "https://cdn.jsdelivr.net/npm/three@latest/examples/jsm/controls/OrbitControls.js";
  import { GLTFLoader } from "https://cdn.jsdelivr.net/npm/three@latest/examples/jsm/loaders/GLTFLoader.js";

  // Code for rendering the scene

</script>

Answer №2

When referencing the documentation for GLTFloader, it is important to note that the url parameter passed to .load() must be a String.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — A string containing the path/URL of the .gltf or .glb file.

To ensure this, you can assign the URL to a variable and then use it with the loader function:

let url = "" + MODEL;
LOADER.load( url, (gltf) =>  ...

-jg-

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

Issues arise when attempting to use the Android KeyUp, KeyDown, and KeyPress events in conjunction with Angular2

I am encountering an issue where I consistently receive a keyCode of 229 in Android Chrome browsers when running either: <input type="text" (keydown)="testKeyCodes($event)"/> <!-- or --> <input type="text" (keyup)="testKeyCodes($event)"/& ...

When setting the request header in XMLHttpRequest, the $_POST variable will be null

I encountered an issue while trying to send a request using XMLHttpRequest in JavaScript code with PHP. Whenever I set the request header using `setRequestHeader`, the `$_POST` value returns null. However, if I remove `setRequestHeader`, the `$_POST` data ...

Tips for eliminating the domain name from the src URL attribute using Jquery

Is there a way to extract the img src attribute and retrieve only the image path without the domain name included? var imgurl = "http://nitseditor.dev/img/home/bg.jpg"; For instance, I would like to display img/home/bg.jpg instead of the full URL. Any id ...

Is there a term similar to "Rise above the Rest" in the world of Web Development?

Hey, I've encountered a new issue right now. Currently, I have two elements that are fixed to the top and bottom of the page. However, the elements in between them are overlapping the top element. Even though I tried keeping both elements fixed, th ...

Filtering nested arrays in Angular by cross-referencing with a navigation menu

In the legacy application I'm working on, we have a navigation menu along with a list of user roles. Due to its legacy nature, we have accumulated a significant number of user roles over time. The main goal is to dynamically display the navigation me ...

Setting attributes to a DOM element using String in jQuery

I am currently facing a challenge where I have a list of attributes saved as a string variable, and I need to add that variable to a <div>. Unfortunately, I am stuck and uncertain about the best approach. Here is what I have so far: HTML: <div&g ...

Including an <a> tag within a JavaScript variable to utilize in an HTML statement

I want to wrap an <a> element around a JavaScript variable containing a string. The desired output should be the 'copyright symbol' followed by the 'companyName' linked as an HTML link and then the current year's date. JavaS ...

JavaScript toggle display function not functioning properly when clicked

I've been attempting to create a drop-down list using HTML and JavaScript, but for some inexplicable reason, it's just not functioning as expected despite scouring through countless tutorials on YouTube. Below is the snippet of code that I'm ...

JavaScript's functionality akin to PHP's exec() function

I am searching for a way to run a shell command through javascript, similar to the functionality of PHP's "exec()" function. I understand that executing shell commands in javascript may not be recommended due to security concerns. However, my javascri ...

Ways to verify if the CSS background-color is set to white?

I am looking for a solution: $('*').click(function() { if($(this).css("background-color") == "#ffffff") { $(this).css("background-color") == "#000000" } });​​​​ that will execute on click of a specific cla ...

Sending an incorrect value to the data variable

Apologies for my limited proficiency in English, Hello, I am new to Vue and struggling with an issue that I can't seem to resolve. I am fetching art data from an API (a simple list of dictionaries), and then creating a multi-array structure (list of l ...

Is it possible to customize the Menu hover effect in Element Plus and Vue?

Hello everyone, I'm a beginner with Vue, HTML, CSS, and Element Plus. I am trying to customize a Side Bar Menu with my own hover effect, but it doesn't seem to be working. Whenever I change the background color of the el-menu element, the hover e ...

Concealing divs without values in ASP.NET MVC

I am working on an AJAX call to fetch data from the back-end and populate divs with it. Below is my code for the AJAX call: $(document).ready(function() { question_block(); }); function question_block() { $.ajax({ url: '@Url.Action(" ...

A guide on iterating through an array to extract the initial character from every string

Currently, my focus is on extracting the initial letter of each word in order to create an acronym. I have set up an array where all the capitalized words are stored, and now I need a way to extract those specific characters. To achieve this, I initially ...

Utilizing Javascript to interact with GroupMe API through POST method

I've been working on creating a client for GroupMe using their provided API, but I'm stuck and can't seem to figure out what's going wrong. curl -X POST -H "Content-Type: application/json" -d '{"message": { "text": "Nitin is holdi ...

Fetching data in React using AJAX

I am in the process of developing a React Component that will display data retrieved from an AJAX call. Here's my scenario - I have a Jinja Flask back end hosted on AWS API Gateway, which requires custom headers and the Authorization header to serve H ...

Determine the quantity of characters available in a contenteditable field

I have implemented a directive that allows me to input editable content inside a tag Recently, I made modifications to include a character counter feature. However, I noticed that when I add line breaks, the character count increases erroneously. https: ...

Unable to retrieve the following element in a JavaScript array

I am a beginner in JavaScript and I am attempting to access the next element of an array using an onclick function but so far I have not been successful. var i, len; function quiz() { var quiz_questions = [ "who is the founder of Fa ...

What is the best way to create a button that will trigger a modal window to display a message?

I am looking to create a button that will open a modal window displaying a message. However, when I tried to add a label and viewed the page, the desired window appeared on top of the rest of the content. But unfortunately, clicking the button did not prod ...

The process of extracting text from an HTML element using Selenium and Node.js

After searching extensively on stackoverflow, I came up empty-handed in finding a solution to my problem. Can anyone lend a hand? I am trying to extract the text from an HTML element using the following code: var element = driver.findElement(webdriver.By ...