When working with three.js, I am able to successfully display a .glb 3D model locally. However, when trying to view it on the GitHub server

While working on my personal webpage, I attempted to use three.js to showcase a 3D model. The model appeared successfully on my local server, but failed to display on my web server, resulting in an error message similar to the following: https://i.sstatic.net/KqJ1d.png

(refer to my .glb file, the main.js, and the index.html file)

After inspecting the HTTP response data of my .glb model using my browser's web tools, I noticed the data resembled the image found here:

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

I would greatly appreciate any insights or suggestions on how to resolve this issue.

Answer №1

BH

The main.js file is currently structured like this:


$(document).ready(function(){

  $nav = $('.nav');
  $toggleCollapse = $('.toggle-collapse');

      /** click event on toggle menu */
  $toggleCollapse.click(function(){
      $nav.toggleClass('collapse');
  })


});

It's difficult to pinpoint the exact issue at the moment, but it seems to have changed from before.

One way to load models without a server is by creating an HTML file that generates a JavaScript loadable file with the data URL of the loaded file. This file can then be included in the main HTML file using a standard script tag. With the THREE.JS model loader, you can simply use the dataURL instead of the model URL.

I have personally used this method numerous times without any server, even without a local server, and successfully loaded various models and files.

An example HTML file / code structure would appear as follows:

BH
<br>
data URL-ifier
<br>
<input id="filePicker" type="file">
<br>
<div id="kinTayner"></div>
<script>
filePicker.onchange = () => {
  var fr = new FileReader()
  fr.onload = () => {
    a = document.createElement("a")
    kinTayner.innerHTML=""
    a.download = filePicker.files[0].name+".html"
    a.innerHTML = "Download the DATA-Urlifier file?"+
  "<br>On GitHub might have to right click->save link as"
    var id=Date.now()
    a.href = URL.createObjectURL(new Blob([
      `
        Duel HTML and JavaScript File,
        \ncan be opened in browser and
        \nincluded as a script, since JavaScript
        \ndoesn't recognize HTML tags in comments,
        \nand JS comments don't affect HTML
        <script>
        
        if(!window.dataURLified) {
          window.dataURLified = function(d) {
            window._fileData_${id} = d;
            var m = document.getElementById("${id}")
            if(!m) return;
            m.innerHTML = "<h1>Your file data!</h1>"+
            "<br><h2>"+d.name+"</h2><br>"+
            "<a href='" + d.url + 
            "' target='_blank'>View your file [or right click to download]</a>"
          }
        }
        </`+`script>
        <div id="${id}"></div>
        <style>
        </style>
          
        */
        dataURLified({name:"` +
          filePicker.files[0].name + `", url: "`+
          fr.result
        +`"})
      `
    ], {type:"text/html"}))
    
    kinTayner.appendChild(a)
  }
  
  fr.readAsDataURL(filePicker.files[0])
}
</script>

Then in your main code, you can read it by including a script with that name (even if the extension is .html) and define a global function dataURLified (or any other name you choose) to handle the data. Below is an example file code to be used after the above file is generated and placed in the same directory:

<h2>BH</h2><br>
<h3>HTML Fileized Loader</h3>
<input id="loader"> -- enter the name of the file you want to load as a script (that was generated before)
<script>
    var files = []
    function loadSc(name) {
        return new Promise((r,j) => {
         var sc = document.createElement("script")
         sc.onload=()=>{
            r({msg:"Loaded",fl:files[files.length-1]}) 
         }
         sc.onerror=(e)=>{
            j({msg:"Nope",details:e}) 
         }
         sc.src=name;
         document.body.appendChild(sc)
        })
    }
    
    function dataURLified(d) {
        files.push(d)
    }
    
    loader.onchange = () => {
        loadSc(loader.value)
        .then(r=> {
            console.log(myFile=r.fl,r.msg,"Use myFile.url for the path!")
        }).catch(e=>{
            console.log("Problem!",e)
        })
    }
</script>

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

Improving code efficiency for checkboxes in upcoming TypeScript versions

Is it possible to create a single checkbox component and dynamically pass different values to it without repeating code? I have set up these checkboxes to help me check the maximum and minimum values of some API data. const[checkValMax, setCheckValMax]= u ...

What is the procedure for updating or adding data to a JSON file with angularJS?

After successfully creating a local JSON file and retrieving data from it using app.controller('appCtrl', function($scope, $http){ $http.get('employees.json').success(function(data){ $scope.employees=angular.fromJson(data.employee ...

Starting a Vue.js app with preloaded data

I have a single file component named Foo: <template> <div> This is the main app. X is {{ x }}, y is {{ y }} </div> </template> <script> export default { data() { return { x: 'hello x' }; }, } </script> ...

What is the method to execute a function on the existing page when the browser goes back?

DESCRIPTION: In order to create a seamless transition between pages on my website, I have implemented a white opaque overlay layer that fades in and out. When a user clicks on a link, a script is activated which prevents the default behavior, fades the inv ...

What is the best way to acquire an ID that is generated dynamically?

Being new to javascript and ajax, I am facing a challenge. I have a while loop with 2 buttons, both of which seem to function correctly, except for one small issue... The product-id is only being passed for the first or last element in the loop. How can I ...

What to do while waiting for MySQL query in an asynchronous function?

Having an issue with my asynchronous function that queries the database using the mysql library. It seems like the function is not waiting for the query to complete before moving on. Here's the code snippet: async (eventName, eventArgs, app) => { ...

Dealing with the Back Button Problem in History API and History.js

Using Ajax to load the page presents a challenge when the user clicks the back button. Here is the scenario: Initial page (index.php) is loaded User clicks on a link The new page loads successfully via Ajax User clicks the back button The initial page is ...

Express.io is encountering an issue where it is unable to read the property 'expires' of an undefined element

I am new to working with node.js and I am attempting to utilize express.io for saving cookies. Following a tutorial at https://github.com/techpines/express.io/tree/master/examples#sessions, I have encountered the following error: root@server1 [/nodeexamp ...

Finding the value of an input without having to submit it first and searching for it within a datalist

> Here is an example of HTML code <label>Person</label> <input name="PersonID" type="text" id="PersonID"> <label>Car Plate Number</label> <input name="PersonsCarPlateNumber" list="PersonsCarPlateNumbe ...

Integrating external information with components

Currently in my React application, I am fetching a list of stores by directly calling the API through the URL. const getStore = async () => { try { const response = axios.get( 'http://localhost:3001/appointment-setup/storeList& ...

Combining Javascript and Django for a powerful web development solution

Having trouble setting up JS on my Django web app, despite reading through the documentation and previous queries. Using the Django dev server with the following file structure: mysite/ __init__.py MySiteDB manage.py settings.py ...

How can we create a two-dimensional image with random dimensions using Math.random?

I am struggling to create a variety of flowers with different sizes from an Array. The issue I'm facing is that every time I click to add a new flower, it changes the size of all existing flowers as well. What I would like is for each added flower to ...

Error: The property 'create' of undefined cannot be read (Material UI/enzyme)

When I mount a component, I encounter an error that does not occur when using shallow rendering. The specific error is: TypeError: Cannot read property 'create' of undefined at stylesOrCreator (node_modules/@material-ui/core/CircularProgress/C ...

commenting system through ajax across multiple web pages

Experimenting with the webcodo comment system has led me to this URL: Database table: "comments" CREATE TABLE IF NOT EXISTS `comments` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(40) NOT NULL, `email` varchar(60) NOT NULL, `comment` te ...

Issues persist with AngularJS integration using Modernizr

Incorporating AngularJS and Modernizr, I aim to identify media queries and trigger a function whenever the window or viewport is resized. My goal is to control element visibility based on whether the user is on a desktop or mobile device - certain elements ...

The combination of Angular Hottowel's 'blocks.exception' and 'blocks.router' prevents the App from being displayed in the browser

After delving into Angular's fundamentals a couple of months back, I am now venturing into building a practice app that mirrors industry standards. I recently completed John Papa's Play by Play and Clean Code courses on Pluralsight, which furthe ...

What is the best way to extract hover-box information from an ajax website with Python?

Attempting to extract the dimensions for each cell on a map from this AJAX site, where details only appear when hovering over the cells has proven unsuccessful so far. Using Python selenium webdriver and phantomJS did not yield any data when trying to loa ...

Guide on Implementing Link href in Next.js v12

When I set the href as a string, the link functions properly. However, when I use an object for the href, the link fails to work. Despite seeing the correct querystring when hovering over the link, it always takes me back to the first page. // ProdCard t ...

"Encountered an issue while serializing the user for session storage in Passport.js. Have you already implemented code for

I have recently started learning nodejs and I am currently working on creating a login system. I followed the code for serializing the user from the passport documentation and placed it in config/passport.js. However, I keep encountering the error "Failed ...

When using Intl.DateTimeFormat, unexpected output may occur when formatting dates prior to the year 1847

Why do dates before 1848 result in May 10 when formatted? Could this be related to time zones? And if so, how can I prevent this issue when creating a date object from an ISO date string like YYYY-MM-DD format? (Tested on Chrome 59) const workingDate ...