Why is there nothing showing up on the screen?

Just diving into Three.js and might've messed up somewhere. I'm trying to generate a geometry by using coordinates and surface data from a .k file. I checked the geometry.vertices and geometry.faces, they seem fine. I even played around with the camera position, but nothing is appearing on the screen. Any help is appreciated!

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

var geometry = new THREE.Geometry();
var map = {}; // mapping node id to index in geometry vertices

// reading in k file line by line
document.getElementById('file').onchange = function(){
    var file = this.files[0];
    var reader = new FileReader();
    var node_flag = false, element_flag = false;

    reader.onload = function(progressEvent){
        var lines = this.result.split('\n');
        for(var line = 0; line < lines.length; ++line){
            if(!node_flag && lines[line].substr(0,5) == "*NODE") {
                node_flag = true;
                continue;
            }
            if(lines[line].substr(0,8) == "$# title")
                node_flag = false;
            else if(lines[line].substr(0,14) == "*ELEMENT_SHELL") {
                element_flag = true;
                continue;
            }
            else if(lines[line].substr(0,14) == "*ELEMENT_SOLID")
                break;
            // reading nodes and creating vectors
            if(node_flag) {
                let data = lines[line].match(/\S+/g);
                map[data[0]] = geometry.vertices.length-1;
                geometry.vertices.push((new THREE.Vector3(+data[1], +data[2], +data[3])));
            }
            // reading element shell and creating surfaces
            if(element_flag){
                let data = lines[line].match(/\S+/g);
                geometry.faces.push(new THREE.Face3(map[data[2]], map[data[3]],map[data[4]]));
            }
        }
    }
    reader.readAsText(file);
    finish_loading();
}

var material = new THREE.MeshBasicMaterial( { color: 0xffffff } );
var cube;

var axesHelper = new THREE.AxesHelper( 5 );
scene.add( axesHelper );

camera.position.z = 100;


function animate() {
    requestAnimationFrame( animate );

       cube.rotation.x += 0.1;

    renderer.render( scene, camera );
}


function finish_loading(){
    cube = new THREE.Mesh( geometry, material );
    scene.add( cube );
    animate();
}
<!DOCTYPE html>
<html>
<head>
<title>MDP Web-tool</title>
    <link type="text/css" href="css/style.css">
    <script src = "js/library/three.js"></script>
    <script src="js/library/node_modules/hashmap/hashmap.js"> </script>
</head>
<body>
    <canvas id = "myCanvas"></canvas>
    <input type="file" id="file">
    <script src="js/model.js"></script>
</body>
</html>

Answer №1

Make sure to place the finish_loading() function after the for loop and not outside your onload callback. This way, it will get executed at the right time, after the onload callback fires.

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

Utilize the jsTimezoneDetect script to showcase a three-letter time zone code

I'm currently utilizing the jsTimezoneDetect script to identify the user's current timezone. The code below shows the result as America/Chicago. Is there a way to display CDT/CST instead (based on today's date)? var timezone = jstz.determin ...

Define the format for the output file name in TypeScript

I am trying to change the filename of a TypeScript generated js file. How can I accomplish this? For instance, I currently have MyCompany.ClassA.ts The default output filename is MyCompany.ClassA.js However, I would like the output filename to be MyComp ...

Leveraging Ajax for transmitting JSON data and performing decoding operations

Previously, I used an AJAX script to fetch data from viewCommentsJson.php. The data retrieved looked like this: [{"comments":"Greta"},{"comments":"John"}]. Is there a way to decode and display this return value properly? Appreciate any assistance. Gret ...

Convert a pandas dataframe into a JSON object with nested structures

Someone raised a similar question in a different forum, which was expertly answered by user1609452 using R. However, I believe there is more to explore with this topic. Let's consider a table (MyData) that looks like this: ID Location L_size L_co ...

What is the best way to remove an object from an array in MongoDB?

I am currently using MongoDB and Node.js, but I am facing a small issue when trying to delete an object from an array of objects. Below is the code snippet causing the problem: router.route('/deleteGuestFromJam/:id').delete(function(req, res){ ...

Encountering issues with Vue 2.5 dynamic dropdown clicks not working as expected

Creating a dynamic dropdown with Vue.js 2.5 A static dropdown menu example: <ul class="dropdown-menu" role="menu" id="dropdown"> <li><a href="#" v-on:click="setDate('2018-11-11')">2018-11-11</a></li> <li> ...

Is there a way to make a string evaluate inline using JavaScript and React?

In my function, the following code works perfectly: console.log(theme.colors.blues[1]); To make the last part dynamic, I tried the following approach: const getColor = (theme, passedColorProp) => { console.log(theme.colors.[passedColorProp]); }; g ...

Enhancing code branch coverage using Istanbul

The code snippet provided has a branch coverage of only 50% (refer to the coverage report below). I am unsure how to enhance this as there are no if statements present. I suspect that Istanbul must utilize some form of measurement that I have yet to grasp ...

Adjusting the background hue of the 'td' element within an ajax request

When I press a button, an ajax call is triggered below. In this call, I append 'td' elements with values to a table. Specifically, on the line ''</td><td>' + result[i].preRiskCategory +', I am attempting to change ...

Adjusting the rotation transform by deleting and reapplying canvas is causing the chart to not display data after redrawing

I am facing a challenge with my previous issue and I am exploring different solutions. One approach I am considering is to remove the canvas element completely and then re-add it, effectively resetting all rotations on the canvas. Although this method alm ...

Angular.js dynamically changing ng-class based on long-polling updates to a monitored variable

Currently utilizing angular.js for my project. I am implementing long polling with a server and would like to dynamically update an element in the view, specifically one with a class of 'updated', whenever the value of build_tag is incremented. ...

How can data be transferred between web pages using jQuery or JavaScript?

Imagine having two different pages on a Classified car website: The first page is the search page, which displays a list of all cars. Check out a sample search page here The second page is the details page, where you can find specific information about a ...

An ultimate guide to mapping a nested array in React.js

Problem: I am struggling to display the entire content of my array. The goal is to render all elements in the array, but so far I can only get one to show up. I have found that including [key] in the object fields is the only way to generate any output. ...

Does anyone have a solution for resetting the ID numbers in a flatlist after removing an item from it?

As the title suggests, I am facing an issue with the following scenario: { id: '1', name: 'one' }, { id: '2', name: 'two' }, { id: '3', name: 'three' }, { id: '4', name: &apo ...

Issue with click function not activating in Chrome when using Angular 6

I am facing an issue where the (click) function is not triggering in my select tag when I use Google Chrome, but it works fine in Mozilla. Below is my code: <div class="col-xl-4 col-lg-9"> <select formControlName="deptId" class="form-control ...

What are the steps to transform my database object into the Material UI Table structure?

I have a MongoDB data array of objects stored in products. The material design format for creating data rows is as follows: const rows = [ createData('Rice', 305, 3.7, 67, 4.3), createData('Beans', 452, 25.0, 51, 4.9), createData ...

What is the best way to identify different directives within the same $scope?

When it comes to calling directive functions from controllers, I follow this approach: function myControllerFunction = function () { $scope.highlight(); } The highlight() function is defined within the directive itself. But what if there are two dif ...

Changing the size on click using Jquery

I'm attempting to make a button shrink another element using jQuery. Here's what I have so far: $( "#img1" ).click(function() { $("#img2").css("-moz-transform:scale", "0.7, 0.7"); }); However, this solution doesn't seem to be functio ...

Sorting through mongoose information on the front end using EJS depending on a dropdown pick

Beginner embarking on my inaugural project here. I have developed 2 Mongoose schematics and models for managing categories and products. The products are nested within the corresponding categories model. Using Node and Express, I successfully sent all ca ...

The Controller received a JSON object that was empty

I know this question has been asked countless times, but I've tried all solutions with no success. Here's the JSON object in question: { "manufacture":"HP", "model":"testModel", "serialNumber":"testSerial", "description":"Test Descript ...