Anyone have a solid example of STLLoader.js code to kickstart a project in three.js? Looking for a clean and reliable snippet

I am looking to add the STLLoader.js from three.js to my web application, but I am struggling to find clean and easy-to-understand code examples on how to get started.

While the official three.js website offers a demonstration example for the STLLoader (here), I have been unable to locate simple sample code specifically for the STLLoader. The only available resource is this example, which can be challenging for beginners to grasp. This stands in contrast to other loaders like the OBJLoader, where clean sample code is easily accessible (here)...

Any assistance with this would be greatly appreciated :)

Answer №1

Here is my final solution for those who were struggling with it too 😄

Below is the HTML code:

<!DOCTYPE html>
    <head>
        <meta charset="utf-8">
        <title>STLLoader Test</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <script src="three.js-master/build/three.js"></script>
        <script src="three.js-master/examples/jsm/controls/OrbitControls.js"></script>
        <script src="three.js-master/examples/jsm/loaders/STLLoader.js"></script>
        <script src="js/custom.js"></script>
    </body>
</html>

For the custom JS (custom.js):

// This part is crucial for camera and plane rotation
var degree = Math.PI/180;

// Setting up the scene, camera, and renderer
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);

// Resizing after viewport-size-change
window.addEventListener("resize", function () {
    var height = window.innerHeight;
    var width = window.innerWidth;
    renderer.setSize(width, height);
    camera.aspect = width / height;
    camera.updateProjectionMatrix();
});

// Adding controls
controls = new THREE.OrbitControls(camera, renderer.domElement);

// Ground setup (comment out line: "scene.add( plane );" if Ground is not needed...)
var plane = new THREE.Mesh(
    new THREE.PlaneBufferGeometry(500, 500 ),
    new THREE.MeshPhongMaterial( { color: 0x999999, specular: 0x101010 } )
);
plane.rotation.x = -90 * degree;
plane.position.y = 0;
scene.add( plane );
plane.receiveShadow = true;

// Importing STL file in ASCII format
var loader = new THREE.STLLoader();
loader.load( './stl/1.stl', function ( geometry ) {
    var material = new THREE.MeshLambertMaterial( { color: 0xFFFFFF, specular: 0x111111, shininess: 200 } );
    var mesh = new THREE.Mesh( geometry, material );
    mesh.position.set( 0, 0, 0);
    scene.add( mesh );
} );

// Importing STL file in binary format
loader.load( './stl/2.stl', function ( geometry ) {
    var material = new THREE.MeshLambertMaterial( { color: 0xFFFFFF, specular: 0x111111, shininess: 200 } );
    var mesh = new THREE.Mesh( geometry, material );
    mesh.position.set( 0, 20, 0);
    scene.add( mesh );
} );

// Setting camera position
camera.position.z = 100;
camera.position.y = 100;
camera.rotation.x = -45 * degree;

// Adding ambient light (needed for Phong/Lambert-materials)
var ambientLight = new THREE.AmbientLight(0xffffff, 1);
scene.add(ambientLight);

// Rendering the scene
var render = function () {
    renderer.render(scene, camera);
};

// Running the game loop (render,repeat)
var GameLoop = function () {
    requestAnimationFrame(GameLoop);

    render();
};

GameLoop();

Lastly, make sure to download the three.js project and include it in your project root.

Cheers, Leon

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

Utilizing hooks to pass properties from a parent component to a child component

As someone who is new to react, I am currently facing an issue with passing props from a parent function to a child. It seems that the parameters "square_state" and "setSquare_state" are not being recognized in the useSquare or handle_square_click functi ...

The implementation of SetInterval within nested functions in JavaScript appears to be malfunctioning

I am a beginner in the world of JavaScript and I am currently attempting to incorporate the setInterval method within functions in Js. JavaScript Code: var tar = document.getElementById("sample"); function dataSample(tar) { //setInterval ...

Enhancing the functionality of hidden input fields using jQuery

I'm looking to dynamically update the value of a hidden input element when a button is clicked. Here's what I have so far: Hidden Input Element: <input type="hidden" value="action" id="action" /> Buttons: <INPUT name=submit value=~#S ...

Deliver an intentionally bogus HTTP response using Express

I'm currently working on creating test cases for a web application and I am interested in testing how well the client can handle invalid HTTP responses. Can you provide some suggestions on how to purposely mess up a response so that it is no longer va ...

Receive multiple JSON objects via an MVC4 controller using AJAX POST method

Is there any way to send multiple objects to a controller using AJAX? What should the data for the ajax post look like? [HttpPost] public string Register(UserLogin userLogin, Contact contact) { } UserLogin public class UserLogin { public string User ...

Updating HTML content based on an active user session using Node.js/Express - A Step-by-Step Guide

I'm struggling to find a way to remove the login/signup buttons once a user has successfully logged in. The issue lies within my header file that needs some modification. <section class="header"> <div class="wrapper"> <nav ...

Angular2+ does not return any elements when using .getElementsByClassName() even if they are present

I have a question that seems simple, but I can't seem to find the answer anywhere. I've looked through past questions but still haven't found a solution... In my Angular template, there is a large amount of text inside a div, and some parts ...

Developing a custom camera system for a top-down RPG game using Javascript Canvas

What specific question do I have to ask now? My goal is to implement a "viewport" camera effect that will track the player without moving the background I am integrating websocket support and planning to render additional characters on the map - movement ...

Using Python with Selenium and JavaScript for Logging in

When using Selenium and Python, I am attempting to log in to a website but encountering difficulties. The issue is that the source code does not display the necessary Id=apple_Id required for sending login information, although it can be seen when inspecti ...

Getting Started with the Basic Example of Redux-Router

Recently, I decided to give redux-router a try and wanted to run the basic example. However, when I tried running the command: npm start I encountered an error message that said: node: bad option: -r Being new to the JavaScript modern ecosystem, I&apos ...

Minimizing the gap between icon and label text

I have a React form that I need help with. The issue is that I want to reduce the space between the list icon and the label. Here is the CSS I am using: .form__container { display: flex; flex-wrap: wrap; } .form__container input { color: rgb(115, 0, ...

Exploring the potential of Apollo React Hooks through Jest and React Testing Library

I am working on a form that utilizes an Apollo mutation hook: import React from 'react' import { useFormik } from 'formik' import { useLoginMutation } from '../generated' const LoginContainer = () => { const [loginMutat ...

What is the best way to sort the values of an associative array in JavaScript?

Consider the following associative array: array["sub2"] = 1; array["sub0"] = -1; array["sub1"] = 0; array["sub3"] = 1; array["sub4"] = 0; How can you efficiently sort this array in descending order based o ...

Implement two different styles within an element's style properties

Welcome everyone, I have a question regarding adding marquee effects to a table row along with highlighting it. Is it possible to include moving text from left to right in the same active row? For example, let's say that the current time is 12:45 AM. ...

Determine the viral coefficient based on the sharing platform being used, whether it is Facebook or Twitter

Traditionally, the viral coefficient is measured through email addresses. For example, if a current user [email protected] invites 10 people via email, you can track how many signed up and calculate the viral coefficient based on that. But what if th ...

What is the best way to arrange the keys of a JavaScript object in a customized

I am struggling to find a way to custom sort a JavaScript object properly. For example, I have the following object: var test = { 'yellow': [], 'green': [], 'red': [], 'blue': [] } And an array with values ...

Menu design with child element creatively integrated into parent element

For my mobile project, I am working on creating a window blind effect menu. The process is quite simple: Clicking on the menu icon moves the bar to the top while the menu drops down Upon selecting an item, the menu smoothly "rolls" up in a window blind s ...

What could be causing the state of a child component to continuously reset?

I have a complex system of React components designed for fetching an embed from a music service API. This includes a higher-order component that interacts with the API to load the embed data. The issue I am facing is that my lowest-level child component is ...

The error message encountered with React Easy DatePicker is: "Uncaught ReferenceError: process is not defined."

I am attempting to integrate the stylish DatePicker from https://www.npmjs.com/package/sassy-datepicker?activeTab=readme Here is my implementation : import DatePicker from "sassy-datepicker"; function App() { const [date, setDate] = useSta ...

Boost the font size on Bootstrap UI Angular timepicker for a better user experience

Is there a way to adjust the font size and width of the timepicker control in Bootstrap UI Angular? Specifically, I am looking to make the text larger and increase the size of the Chevron (up/down buttons). Here is the code snippet I currently have: < ...