A guide on importing gLTF files into three.js

I've been having some trouble uploading a gLTF file using three.js. Despite fixing some errors, I'm still greeted with a black screen. One solution was adding this to my chrome target directory:

‘path to your chrome installation\chrome.exe --allow-file-access-from-files’ 

This fixed the issue momentarily, but I continue to receive the following error when checking the console: https://i.sstatic.net/9AD76.png

Could someone provide assistance? All I want to do is display the 'DamagedHelmet.gltf' file on the screen with three.js.

The error occasionally resurfaces, and here's how it appears: https://i.sstatic.net/FivB7.png The code:

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Three.js Crash Course</title>
        <style>
            body {
                margin: 0;
            }
            
            canvas {
                width: 100%;
                height: 100%;
            }
        </style>
    </head>
    <body>
        <script src="js/three.js"></script>
        <script src="js/OrbitControls.js"></script>
        <script src="js/GLTFLoader.js"></script>
        <script>
            // To display anything we need three things: scene, camera, renderer.

            var scene = new THREE.Scene();
            var camera = new THREE.PerspectiveCamera(75/*POV*/, window.innerWidth / window.innerHeight/*aspect ratio so it takes on the size of the screen*/, 0.1, 1000);
            
            var renderer = new THREE.WebGLRenderer();//API for rendering/processing 2D and 3D to browsers
            renderer.setSize(window.innerWidth, innerHeight); // Size you want it to render which is size of screen/area
            document.body.appendChild(renderer.domElement); // Add the renderer to the HTML document/canvas
            
            controls = new THREE.OrbitControls(camera, renderer.domElement);
            //-------create shape you need geometry, material/apperance and cube

            var loader = new THREE.GLTFLoader();
            
            loader.load(
                // Resource URL
                'models/gltf/duck/gLTF/duck.gltf',
                // Called when the resource is loaded
                 function ( gltf ) {

                     scene.add( gltf.scene );
                     camera.position.z = 5;
                     gltf.animations; // Array<THREE.AnimationClip>
                     gltf.scene; // THREE.Scene
                     gltf.scenes; // Array<THREE.Scene>
                     gltf.cameras; // Array<THREE.Camera>
                     gltf.asset; // Object 
                 },

                 // Called when loading is in progresses
                 function ( xhr ) {
                     console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );

                 },

                 // Called when loading has errors
                 function ( error ) {
                     console.log( 'An error happened' );
                 }
             );
            
            var animate = function() {
                requestAnimationFrame(animate);
                // cube.rotation.x += 0.01;
                // cube.rotation.y += 0.01;
                renderer.render(scene, camera);
            }
           
            animate();
        </script>
    </body>
</html>

Answer №1

Referencing directly from the official three.js manual:

Executing Local Operations
When utilizing procedural geometries without loading any textures, webpages should function seamlessly from the file system. Simply double-click on the HTML file within a file manager and it should open and run in the browser (you will notice file:///yourFile.html in the address bar).

Loading Content from External Sources If you are loading models or textures from external files, browser security restrictions based on the same origin policy prevent successful loading from the file system, resulting in a security exception.

There exist two solutions to this issue:

  1. Adjust security settings for local files in your browser. This enables access to your page via: file:///yourFile.html
  2. Operate files from a local web server. This allows access to your page through: http://localhost/yourFile.html

If you opt for option 1, be mindful of potential vulnerabilities when using the same browser for regular web browsing. Consider creating a distinct browser profile or shortcut solely dedicated to local development for increased safety. Let's explore each option further.

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

Diverse Browser Outcomes with jQuery CSS

Currently, I am in the process of developing an app that utilizes percentages as offset positions for ease of calculation. For a visual example, you can visit this link: http://jsfiddle.net/WeC9q/1/embedded/result/ Although the zooming feature functions ...

Looking to display or conceal a text box with a date picker based on the selection of a specific value from a drop-down menu

I have a dropdown with two options: Indian and Others. When I select Others, I want to display three textboxes - two with date pickers and one with a simple text input field. I have tried writing the following HTML code but I am unable to get the date pick ...

What is the best way to clear the selected option in a dropdown menu when choosing a new field element?

html <div class="row-fluid together"> <div class="span3"> <p> <label for="typeofmailerradio1" class="radio"><input type="radio" id="typeofmailerradio1" name="typeofmailerradio" value="Postcards" />Postcards& ...

Guide on using JavaScript to extract and display a random text from a datalist upon clicking with the onclick event

Is there a way for a JavaScript function to select a random sentence from a datalist within the same file and display it upon clicking a button with an "onclick" event? I'm new to JavaScript and seeking the simplest solution. Can anyone provide an exa ...

Gulp encountered an issue - TypeError: When attempting to call the 'match' method, it was found to be undefined

Currently, I'm attempting to utilize Gulp alongside BrowserSync for a website that is being hosted on MAMP and proxied through localhost:8888. Unfortunately, upon running gulp, I encounter the following error: [17:38:48] Starting 'browser-sync& ...

Using Material-UI with @emotion/cache in SSR results in consistently empty cache

After transitioning my React SSR from pure @emotion to material-ui 5.0, I encountered an issue where the styles no longer get extracted. The ID extraction in createExtractCriticalToChunks seems to be functioning correctly, but the cache.inserted object fro ...

Having trouble getting the .replace() Javascript function to work on mobile devices?

I have a code snippet for implementing Google Analytics. Here it is: $(function () { $('.plan-choose-btn a').bind('click', function(e) { //ga load image <% String myaccGAEventUrl = trackGoogleAnalyticsEvent(requ ...

Discover the best method for retrieving or accessing data from an array using Angular

In my data processing task, I have two sets of information. The first set serves as the header data, providing the names of the columns to be displayed. The second set is the actual data source itself. My challenge lies in selecting only the data from th ...

Adjusting the waterlevel model attribute to its standard value

In my Sails.js project, I am looking to reset a model attribute back to its original default value. By default value, I mean the value specified using defaultsTo in the model file. I have attempted methods such as: model.update({id:exampleId}, {myAttrib ...

Generate a hyperlink that directs to a page and triggers the expansion of an accordion section

I am currently working with a Bootstrap 5 accordion component: <div class="accordion" id="accordionIndexPage"> <div class="accordion-item"> <h2 class="accordion-header" id="flush-headingOne& ...

Using Express.js to leverage Vega for generating backend plots

Exploring ways to create plots using backend code and transfer them to the front end for display. Could it be feasible to generate plots on the server-side and then transmit them to the front end? I am interested in implementing something similar to this: ...

Rotating around an object's axis in ThreeJS

Struggling to get an object to rotate around its own axis, but nothing seems to be working. I've tested all the functions listed in the documentation, as well as Euler's method, but no luck - it simply refuses to rotate. ...

Implementing setInterval in ReactJS to create a countdown timer

I have been working on developing a timer application using React. The functionality involves initiating a setInterval timer when a user clicks a specific button. const [timer, setTimer] = useState(1500) // 25 minutes const [start, setStart] = useState( ...

What is the best way to merge multiple chunks of arrays into a single array

What I currently possess: let json = { key1: 'value1', key2: 'value2', key3: { title: 'yeah' } } let path = ['key3', 'title']; My goal is to concatenate segments of the 'path' array ...

Converting Background Images from html styling to Next.js

<div className="readyContent" style="background-image: url(assets/images/banner/banner-new.png);"> <div className="row w-100 align-items-center"> <div className="col-md-7 dFlex-center"> ...

Encountering an NPM error while attempting to initiate a new React application

Having trouble creating a React app due to an npm warning message? Seek assistance, please! npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="19342d2e6a6867687c4b">[email protected]</a>: This ve ...

Database query not appearing on node.js route

As a newcomer to javascript and nodejs, I have encountered an issue that I'm hoping to get some clarification on. I am currently working on a simple API and facing difficulties in understanding why a certain behavior is occurring in my code. app.get( ...

Looking for a character that includes both lowercase and uppercase letters

Here is the JSON data I have: [ {"lastName":"Noyce","gender":"Male","patientID":19389,"firstName":"Scott","age":"53Y,"}, {"lastName":"noyce724","gender":"Male","patientID":24607,"firstName":"rita","age":"0Y,"} ] var searchBarInput = TextInput.value; var ...

Strange behavior in Vue observed. The v-if directive is not properly monitoring changes

I am facing a perplexing issue. I have a basic service and a Vue component. In the template, there is a v-if directive that monitors a variable in the service (if it is true, a div should be displayed, otherwise not). Everything works fine when I initial ...

Import data from JSON using JavaScript

I have a collection of txt files that contain custom content. The file names are stored in a JSON array. { txtFiles: ['./file1.txt', './file2.txt', './file3.txt'] } I am looking to use the require function in JavaScript t ...