M
M
MeinJun2020-07-09 19:06:06
JavaScript
MeinJun, 2020-07-09 19:06:06

How to bind Input file to Three.js canvas?

There is such an STL viewer:

import * as THREE from "https://threejs.org/build/three.module.js";
import {OrbitControls} from "https://threejs.org/examples/jsm/controls/OrbitControls.js";
import {STLLoader} from "https://threejs.org/examples/jsm/loaders/STLLoader.js";
const scene = new THREE.Scene();
scene.background = new THREE.Color( 0xafdafc );
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({canvas: viewer});
renderer.setSize(1200, 600);
const loader = new STLLoader();
loader.load('./models/lamp.stl', function (geometry) {
    const material = new THREE.MeshStandardMaterial({});
    const mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);
});
const controls = new OrbitControls(camera, renderer.domElement);
camera.position.set(0, 20, 100);
controls.update();
function render() {
    requestAnimationFrame(render);
    controls.update();
    renderer.render(scene, camera);
}
render();

And there is an Input file in HTML
<form class="stlviewer" id="stlviewer">
                <input type="file" accept=".stl">
            </form>
            <canvas id="viewer"></canvas>

Question: How to connect them so that through the input it would be possible to load the model into the canvas?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MeinJun, 2020-07-10
@MeinJun

<input id="input" type="file">

var input = document.getElementById( 'input' );
input.addEventListener( 'change', function( event ) {
    var file = this.files[ 0 ];
    var reader = new FileReader();
    reader.addEventListener( 'load', function ( event ) {
        var contents = event.target.result;
        var geometry = new STLLoader().parse( contents );
        var material = new THREE.MeshStandardMaterial();
        var mesh = new THREE.Mesh( geometry, material );
        mesh.castShadow = true;
        mesh.receiveShadow = true;
        scene.add( mesh );
    }, false );
    if ( reader.readAsBinaryString !== undefined ) {
        reader.readAsBinaryString( file );
    } else {
        reader.readAsArrayBuffer( file );
    }
} );

Read more here - https://stackoverflow.com/questions/62832351/how-t...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question