Using THREE.js to load an STL file within the mounted() lifecycle hook in Vue

I am encountering an issue where I cannot load an STL file into a three.js scene that is created using vue.js.

The code structure resembles the following:

<template>
  <div class="GCodeViewer">

    <div id="canvas"></div>
   
  </div>
</template>

<script>
import * as THREE from "three";
import { STLLoader } from 'three/examples/jsm/loaders/STLLoader.js';
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

export default {
  name: "GCodeViewer",
  data: function() {
    return {
      show: this.tabs,
      scene: null,
      renderer: null,
      camera: null,
      controls: null,
      points: [],
      lightHolder: null,
      height: 0,
      object: null,
      nozzle: null,
      raycaster: null,
      mouse: null,
      gcode: ""
    };
  },
  methods: {
    init() {
      var self = this;
      var container = document.getElementById("canvas");
      this.renderer = new THREE.WebGLRenderer({
        clearColor: 0x000000,
        clearAlpha: 1
      });
      var width = (window.innerWidth - 100) / 2;
      var height = window.innerHeight / 2;
      this.renderer.setSize(width, height);
      this.renderer.setClearColor(0xffffff, 1);
      container.appendChild(this.renderer.domElement);

      //this.raycaster = new THREE.Raycaster();
      //this.mouse = new THREE.Vector2();

      this.scene = new THREE.Scene();
      this.scene.background = new THREE.Color(0x50555f);

      var zylinder_mesh = null

      var loader = new STLLoader();
            loader.load( 'stl/example.stl', function ( geometry ) {
               var material = new THREE.MeshPhongMaterial( {
                      ambient: 0xff5533, 
                      color: 0xff5533, 
                      specular: 0x111111,
                      shininess: 200 }
        );
        mesh = new THREE.Mesh(geometry, material);
        mesh.position.set(0, 100, 0);
        self.scene.add(mesh)
      }, undefined, function (error){console.error(error);});

      console.log(this.scene.children)

      this.points.push(new THREE.Vector3(0, 0, 0));

      this.camera = new THREE.PerspectiveCamera(40, width / height, 1, 10000);
      this.camera.position.y = 250;
      this.camera.position.z = 0;
      this.camera.position.x = -300;
      this.camera.lookAt(new THREE.Vector3(0, 0, 0));

      var ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
      this.scene.add(ambientLight);

      this.renderer.shadowMap.enabled = true;
      this.renderer.shadowMap.type = THREE.BasicShadowMap;

      this.controls = new OrbitControls(this.camera, this.renderer.domElement);
    },
    animate() {
      this.controls.update();
      requestAnimationFrame(this.animate);
      this.renderer.render(this.scene, this.camera);
    }
  }
},
mounted() {
    this.init();
    this.animate();
    //window.addEventListener("mousedown", this.onMouseDown, false);
  }
};
</script>

Although everything works fine with creating meshes and adding them to the scene within the init() function, there seems to be an error when attempting to load STL files which suggests that the file may not be found.

GCodeViewer.vue?5fe3:78 RangeError: Invalid typed array length: 6861101076
    at new Float32Array (<anonymous>)
    at parseBinary (STLLoader.js?518e:196)
    at STLLoader.parse (STLLoader.js?518e:393)
    at Object.eval [as onLoad] (STLLoader.js?518e:90)
    at XMLHttpRequest.eval (three.module.js?5a89:36216)
eval @ GCodeViewer.vue?5fe3:78
eval @ STLLoader.js?518e:96
eval @ three.module.js?5a89:36216
load (async)
load @ three.module.js?5a89:36194
load @ STLLoader.js?518e:86
...

I need assistance in finding a way to correctly load the STL file. Any guidance would be greatly appreciated!

Regards, Dominik

Answer №1

Resolution

Transferring the .stl file to the public directory enabled successful importing using base_url/example.stl

Answer №2

Give this a shot:

  1. Install react-scripts using yarn add
  2. Delete the node_modules directory by running rm -rf node_modules/
  3. Run yarn to reinstall dependencies
  4. If the issue persists, consider downgrading Node from version 12 to version 10 as a last resort

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

Is it possible to verify the authenticity of JSON data retrieved from

I'm currently working on validating JSON input from users and came across a challenge. I've found a way to check if the text a user enters is valid JSON using a simple function, like below: function IsJsonString(str) { try { JSON.par ...

Clear the local storage once the URL's view has been fully loaded

When retrieving details of a specific item by passing URL parameters stored in local storage, I encountered an issue. I need to delete the local storage variables after the view is loaded. However, what actually happens is that the local storage variable ...

how to toggle a pre-selected checkbox in a Vue component

https://i.stack.imgur.com/6GQl7.png When dealing with a tree view checkbox in Vue, I encountered an issue where editing data within a selected zone should automatically check the corresponding countries based on previous selections. The ID of the selected ...

Issue with scroll down button functionality not functioning as expected

Is there a way to create a simple scroll down button that smoothly takes you to a specific section on the page? I've tried numerous buttons, jQuery, and JavaScript methods, but for some reason, it's not working as expected. The link is set up co ...

The method Array.find, along with other similar methods, does not automatically return a value of `undefined`

Why does TypeScript in my NestJS environment only infer the return type of Array.prototype.find as T, instead of T | undefined as specified? Is there a way to make TypeScript automatically recognize that find should return T | undefined? ...

Limit certain website functions exclusively for members

I am currently working on a website that offers a set of basic features for all users, along with some exclusive features reserved for members. For example, all visitors can read posts, but only members have the ability to add tags, share posts, and more. ...

What is the best way to loop through the body of a POST request in Express.js?

Currently, I am developing a general route handler for handling POST requests in NodeJS. My challenge is to iteratively go through the req.params of each POST request without having prior knowledge of what the parameters will be. So far, my attempts have ...

Automatically refreshing the canvas whenever the value of an HTML element is modified in Javascript

Below is the javascript code that is relevant <script> $.fn.ready(function() { var source = $('#source').val(); Meme('url1', 'canvas','',''); $('#top-line, #bottom-li ...

Consolidate all scripts into a single file with Asp.net MVC 5 bundling

On one of my razor pages, I have the following script section: @Scripts.Render("~/bundles/script1") @Scripts.Render("~/bundles/script2") @Scripts.Render("~/bundles/script3") The issue is that it renders three separate JavaScript files. Is there a way to ...

AngularJS: Error - Angular object is undefined

Hello! I am currently working on a project to develop a simple App using c# WebAPI and AngularJS. Unfortunately, I have encountered an error in the console which is preventing the web app from functioning properly. Here is a snippet of my Index.html file: ...

How can I make my div change color when the check-box is selected?

I have a dynamic table in my web application that is populated with data from a database. Each row in the table represents multiple time slots for a specific date. I am working on a feature where the background color of a time block can be changed if a che ...

Button to close CSS overlay scrolls to the top of the page

I have managed to create a CSS-only solution where clicking on an anchor displays an overlay image on top of a div. Everything works smoothly except for one issue: when the close button is clicked, it scrolls to the top of the page instead of closing and s ...

What is the best way to connect the "areaName" with the <TextBox> attributes value="" and onChange=""?

After calling an API and mapping the array, I have successfully bound the data on <TableCell> {this.state.allArea.map((allArea, i) => ( <TableRow > <TableCell >{allArea.areaName}</TableCe ...

Optimal Strategy: Utilizing Spring Boot for Backend Development and jQuery for Frontend Interface

I am currently tackling a project that involves a Spring Boot 2 Backend and a jQuery Frontend. The frontend communicates with the backend by sending Ajax requests to Spring REST controllers in order to interact with database entities. One of the challenge ...

Activate a disabled element in Vue.js Datepicker

In my scenario, there are 2 instances of the <date-picker>. The first instance is used for capturing the start date (starts_at), while the second instance captures the end date (ends_at). According to the design I have envisioned, I would like to in ...

JavaScript functions are not being triggered when the submit button is clicked

I am facing an issue where the form buttons are not triggering functions in my React application. The post request is being made using Axios. Could this be related to the structure of my components? Or perhaps it has something to do with file naming conven ...

Can you eliminate the commas and turn it into a string?

function EncryptMessage(message) { var encryptedArr = []; for(i=0;i<message.length+1;i++){ var unicode = message.charCodeAt(i); var encryptedUnicode; var newCharacter = String.fromCharCode(encryptedUnicode); if( ...

Top method for validating a function that generates an observable operator

What is the most effective approach to testing a function that returns an observable with the tap operator? operations(numbers): Observable{ const sumValue = numbers[0]+numbers[1] return sumService.getOperations(sumValue).pipe(tap(randomOperationValue ...

How to delete an item from an array of objects using ReactJS

Hello there, I am currently learning about React Js and I have encountered a problem. I need to remove an element from an array. Here is the structure of my array: array = [{ Id: "L0", value="asas"}] The array that I want to work with is stored in this ...

Performance of Bloom Effect in Three.js

The frame rate ranges from 50 to 60fps without the bloom effect being applied. renderer.render( scene, camera ); However, once the bloom effect is added, the frame rate drops significantly to just 10fps. camera.layers.set( BLOOM_SCENE ); bloomComposer.r ...