Coder Social home page Coder Social logo

gabotechs / react-stl-viewer Goto Github PK

View Code? Open in Web Editor NEW
80.0 2.0 14.0 180.17 MB

React component for visualizing 3d STL models in the browser using three.js

License: MIT License

JavaScript 5.99% TypeScript 94.01%
stl 3d three threejs react obj model 3dmodel render renderer

react-stl-viewer's Introduction

react-stl-viewer

React component for visualizing STLs using Three.js.

Install

npm install --save react-stl-viewer

or

yarn add react-stl-viewer

Usage

import React from 'react';
import ReactDOM from 'react-dom';
import {StlViewer} from "react-stl-viewer";

const url = "https://storage.googleapis.com/ucloud-v3/ccab50f18fb14c91ccca300a.stl"

const style = {
    top: 0,
    left: 0,
    width: '100vw',
    height: '100vh',
}

function App() {
    return (
        <StlViewer
            style={style}
            orbitControls
            shadows
            url={url}
        />
    );
}

ReactDOM.render(<App/>, document.getElementById('root'));

Demo

You can see working the examples from .storybook/stories here

Props

Prop Type Required Notes
url string true url of the Stl file
cameraProps CameraProps false camera properties, see below
modelProps ModelProps false 3d model properties, see below
floorProps FloorProps false floor properties, see below
shadows boolean false render shadows projected by the model on the ground
showAxes boolean false show x y z axis
orbitControls boolean false enable camera orbit controls
extraHeaders Record<string, string> false custom headers for making the http query
onFinishLoading (ev: ModelDimensions) => any false callback triggered when Stl is fully loaded
onError (err: Error) => any false callback triggered when an error occurred while loading Stl
canvasId string false id of the canvas element used for rendering the model

The component also accepts <div/> props

Interfaces

CameraProps

Prop Type Required Notes
ref {current: CameraRef} false reference of the camera for accessing it's properties
initialPosition CameraPosition false set the position of the camera in geographic coordinates. The origin of coordinates is the object itself

CameraRef

Prop Type Required Notes
setCameraPosition (position: CameraPosition) => any true imperatively sets the camera position based on the provided geographic coordinates

setCameraPosition:

ModelProps

Prop Type Required Notes
ref {current: ModelRef} false reference of the 3d model for accessing it's properties
scale number false scale of the 3d model, defaults to 1
positionX number false x coordinate in the world of the 3d model
positionY number false y coordinate in the world of the 3d model
rotationX number false rotation in x axis of the model
rotationY number false rotation in y axis of the model
rotationY number false rotation in z axis of the model
color CSSProperties['color'] false color of the 3d model, defaults to "grey"
geometryProps (geometry: BufferGeometry) => BufferGeometry false Perform some processing to the models geometry

FloorProps

Prop Type Required Notes
gridWidth number false if specified, a grid will be drawn in the floor with this width
gridLength number false if specified, a grid will be drawn in the floor with this length

ModelDimensions

Prop Type Notes
boundingRadius number the radius of the bounding sphere of the 3d model before scaling
width number width of the 3d object
height number height of the 3d object
length number length of the 3d object

CameraPosition

Prop Type Required Notes
latitude number false camera's position latitude, it should be a number between - Math.PI / 2 and Math.PI / 2, if the number exceeds the limits it will be clamped
longitude number false camera's position longitude, it should be a number between - Math.PI and Math.PI, if the number exceeds the limits it will be clamped
distance number false the distance factor between the object and the camera. This is a factor relative to the object size or the grid size if it's specified

react-stl-viewer's People

Contributors

gabotechs avatar kwiniarski97 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

react-stl-viewer's Issues

Is there an example of updating the camera initial position?

Hello there, I'm enjoying using this package in a project I'm working on - however, I am wondering if you have any guidance on using the CameraInitialPosition interface? Since the StlViewer component does not accept that in its props, it's not clear to me how I can update the values for the initial camera position and have my viewer use those.

Provide stl content from string

Hi, this project looks exactly what i was looking for, except that the stl file content must be loaded from a url. In my usecase, the stl file content is dynamically generated client-side. Is it possible to add an option to provide the stl file content directly?

Thanks for the great Work

Low quality render

I have implemented this library in a React + Electron project, but I am facing issues with low quality. This is the standard code that I have implemented:

function ViewSTL() {
    return (
      <StlViewer
        extraHeaders={{}}
        floorProps={{
          gridWidth: 300
        }}
        modelProps={{
          color: '#008675',
          positionX: 150,
          positionY: 150,
          ref: {
            current: '[Circular]'
          },
          rotationX: 0,
          rotationY: 0,
          rotationZ: 0,
          scale: 1
        }}
        orbitControls
        shadows
        showAxes
        width={400}
        height={400}
        style={{
          backgroundColor: 'white',
          height: '100vh',
          left: '0vw',
          position: 'absolute',
          top: '0vh',
          width: '100vw'
        }}
        url="https://storage.googleapis.com/ucloud-v3/ccab50f18fb14c91ccca300a.stl"
      />
    );
}

immagine

Am I doing something wrong?

Problem working in build

It works perfectly in development but after build project, it doesn't load in production. Seems that browser hangs and not responding with no console error
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-stl-viewer": "^2.2.2",

viewer do not showing anything with big files

I am trying to upload "big" files (I see it happens also in 8MB files) and the viewer do not showing anything. sometimes it gives an error in the console (when I try to pan the canvas (empty white canvas), and it is always shows "THREE.WebGLRenderer: Context Lost."
no shadows, grid, or any other props. just the file.
I tried on several PC's and iPhone.
image
Is there a limit for file-size? is there a way to fix that?
I assume it is because of the resolution of the STL file. is there a way to decrease the render quality?
In addition, is there a way to support 3MF, OBJ files?
Thanks in advance.

Originally posted by @LidorCubee3D in #6 (comment)

Can't display STL files by giving file's path

There's a stl file unter dist/static/sample.stl

I tried to set the path into url as below:

class ViewerApp extends Component {

    render(){
        return (
            <div>
                <StlViewer url="dist/static/sample.stl" shadows orbitControls={true} />
            </div>
        );
    }
};

export default ViewerApp;

But, got Error messages

index.esm.js:24207  Uncaught Error: Could not load dist/static/sample.stl: Invalid typed array length: 16221582540)
    at index.esm.js:24207:1
    at Object.onLoad (index.esm.js:25216:1)
    at three.module.js:41500:1
() @ index.esm.js:24207
() @ index.esm.js:25216
() @ three.module.js:41500
index.esm.js:24207  Uncaught Error: Could not load dist/static/sample.stl: Invalid typed array length: 16221582540)
    at index.esm.js:24207:1
    at Object.onLoad (index.esm.js:25216:1)
    at three.module.js:41500:1
() @ index.esm.js:24207
() @ index.esm.js:25216
() @ three.module.js:41500
index.esm.js:10921  The above error occurred in the <SceneSetup> component:

    at SceneSetup (http://www.localhost:3000/static/js/bundle.js:70447:16)
    at Suspense
    at ErrorBoundary (http://www.localhost:3000/static/js/bundle.js:66760:5)
    at FiberProvider (http://www.localhost:3000/static/js/bundle.js:68836:1)
    at Provider (http://www.localhost:3000/static/js/bundle.js:68502:5)

React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.
logCapturedError @ index.esm.js:10921
callback @ index.esm.js:10984
callCallback @ index.esm.js:5453
commitUpdateQueue @ index.esm.js:5474
commitLayoutEffectOnFiber @ index.esm.js:16043
commitLayoutMountEffects_complete @ index.esm.js:17456
commitLayoutEffects_begin @ index.esm.js:17442
commitLayoutEffects @ index.esm.js:17380
commitRootImpl @ index.esm.js:20105
commitRoot @ index.esm.js:19971
finishConcurrentRender @ index.esm.js:19151
performConcurrentWorkOnRoot @ index.esm.js:19068
workLoop @ index.esm.js:551
flushWork @ index.esm.js:524
performWorkUntilDeadline @ index.esm.js:818
index.esm.js:24207  Uncaught Error: Could not load dist/static/sample.stl: Invalid typed array length: 16221582540)
    at index.esm.js:24207:1
    at Object.onLoad (index.esm.js:25216:1)
    at three.module.js:41500:1
() @ index.esm.js:24207
() @ index.esm.js:25216
() @ three.module.js:41500
react-dom.development.js:18687  The above error occurred in the <ForwardRef(Canvas)> component:

    at Canvas (http://www.localhost:3000/static/js/bundle.js:68961:5)
    at FiberProvider (http://www.localhost:3000/static/js/bundle.js:68836:1)
    at CanvasWrapper
    at Suspense
    at ErrorBoundary (http://www.localhost:3000/static/js/bundle.js:70583:43)
    at div
    at StlViewer (http://www.localhost:3000/static/js/bundle.js:70608:16)
    at div
    at ViewerApp (http://www.localhost:3000/static/js/bundle.js:844:1)
    at RenderedRoute (http://www.localhost:3000/static/js/bundle.js:41497:5)
    at RenderErrorBoundary (http://www.localhost:3000/static/js/bundle.js:41448:5)
    at Routes (http://www.localhost:3000/static/js/bundle.js:41987:5)
    at Router (http://www.localhost:3000/static/js/bundle.js:41925:15)
    at RouterProvider (http://www.localhost:3000/static/js/bundle.js:41771:5)

React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.
logCapturedError @ react-dom.development.js:18687

Any suggestion?

Max Zoom Depth

Can you set the max in and out zoom factors?

e.g. I want the model max zoom to be 3 times the size of the original and at least to 0.5 times of the original.

Error after installing react-stl-viewer

Hi guys,

I just installed the react-stl-viewer to test it, but I somehow get the following error:
Failed to compile.

./node_modules/react-stl-viewer/lib/index.esm.js
Module not found: Can't resolve 'three' in 'CUSTOM_PATH/node_modules/react-stl-viewer/lib'

Not sure if this is on my site or if react-stl-viewer just did not install the three.js component.

Looking forward to your help!

Add `OnCameraMoved` prop

This prop will fire an event when the camera position has been moved via orbit controls. This will help with maintaining camera state externally

Set orthogonal or perspective views

Hello there - in my app I'd like to add a button for users to reset the view to an orthogonal view. In another use case, I'd like to set the orthogonal view when the stl file loads.

For example, in OpenSCAD there is a button that does something like this:

Screen.Recording.2023-12-23.at.6.28.24.PM.mov

Is this possible currently, or would it require building out more functionality?

Example usage in readme gives invalid typed array length error

Hello!

I've tried to use the example code snippet from the readme, see here:

image

But it gives me an invalid typed array length.

image

Is there a limit on how big files can the viewer process? If I visit the url provided, I can download the stl file myself, it's about 14 MB. Windows can open it in Paint 3D without any issues and I see the Spider-man head.

I'm using the following versions:

"@types/three": "^0.159.0",
"@react-three/fiber": "^8.15.5",
"react-stl-viewer": "^2.4.0",
"three": "^0.159.0",
"three-stdlib": "2.17.2"

Thanks!

i dont know if i have exactly the same problem, this is my error

i dont know if i have exactly the same problem, this is my error
image
and this my package.json, i am using next.js without typescript and i have install three and react-stl-viewer

{
"name": "example",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "12.2.5",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-stl-viewer": "^2.1.2",
"three": "^0.144.0"
},
"devDependencies": {
"autoprefixer": "^10.4.8",
"eslint": "8.23.0",
"eslint-config-next": "12.2.5",
"postcss": "^8.4.16",
"tailwindcss": "^3.1.8"
}
}

Originally posted by @rmartin177 in #3 (comment)

file prop support gone in version 2.0.0

Hello.
this package seems great, but I can't manage to use a file (from input/drag and drop) in version 2.0.0 and up. did you remove this option? why?
It works well on ver. 1.0.8 tough.
Thanks.

Low Performance in Demo Scene

When using the demo scene on multiple devices it provides a choppy low framerate, especially on version 2+. Brave claims system (self) uses the most time (~400ms).

The fast machine's specs :

  • Ryzen 3600
  • GTX 1070
  • 16GB Ram

Counteract flickering when STL URL is changed

Hi, thank you for the library! I have an issue: I want to switch between STL files being shown, but when the url of the STL file is changed, there is a flickering motion where the new object very shortly is shown in the left-top corner, with only half of the object being visible in the viewport. Only after that is it positioned in the correct initialPosition. Would it be possible to directly render the object in the correct position after STL-change? I would prefer the scene to be temporarily hidden to this flickering motion.

Update peer dependencies

Hi, the peer dependencies need to be updated to match the dependencies. Currently react 18 is used, but the peer deps specify only 17.

Error when installed

When I installed, it had error

Module not found: Error: Can't resolve 'three'
Module not found: Error: Can't resolve 'fs'
Cannot read properties of undefined (reading 'module')

Lighting not working

The stl viewer was working perfectly for me for some time, but recently the displayed models are much darker and have no surface features, just a flat color.

Here's a link to what it looks like: https://drive.google.com/file/d/1uxt93zZnK8UzVrA93_mPZiHieAEbMYwn/view?usp=sharing

The code I am using:

import { StlViewer } from 'react-stl-viewer';

const url = "https://storage.googleapis.com/ucloud-v3/ccab50f18fb14c91ccca300a.stl"

const style = {
    top: 0,
    left: 0,
    width: '100vw',
    height: '100vh',
}

function App() {
    return (
        <StlViewer
            style={style}
            orbitControls
            shadows
            url={url}
        />
    );
}

export default App;

Capture 2D image from 3D render

Is there a way to capture a 2D image of the 3D render? I'm hoping to have a png of each STL file to display as a thumbnail on my website.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.