firtoz / react-three-renderer

Render into a three.js canvas using React.
https://toxicfork.github.com/react-three-renderer-example/
MIT License
1.49k stars 155 forks source link

Adding objects (OBJ) to scene using react-three-renderer #205

Closed zhuber closed 6 years ago

zhuber commented 6 years ago

I'm unable to add object files (obj) to my scene using this package. After looking at the documentation and examples it doesn't seem like it's supported, but I feel like this is a very common use-case for people building things with threeJS.

I have tried a number of different techniques from people who have been trying to solve this same problem, but none of them have worked. Most are very outdated (react moves quickly and things break), so I can't even get them to work without first altering the code to work with updated versions of React. I don't know if one of these approaches will pan out eventually, but the more time I spend on this the more obvious it is that everyone's approach is very different and all of them seem really complicated for just loading a model and material.

Are there any plans to make a recommended workflow/approach for loading objects into a scene in react-three-renderer? An example in the wiki would go a long way and would be much appreciated by anyone trying to do this going forward.

nick-parker commented 6 years ago

I'd also like some documentation on how to do this. For what it's worth, #179 has some good guidance.

You can import a vanilla Three.js geometry object and then use ref functionality to add it to a scene normally. Ie, in your JSX you tag your scene object (or group, whatever you want to add a child to) like so: <scene ref="scene">

Then in ComponentDidMount() you can extract it from refs and add a geometry to it:

componentDidMount() {
    const { scene } = this.refs
    const loader = new THREE.STLLoader();
    loader.load(testfile, (geometry) => {
      console.log(geometry);
      scene.add(new THREE.Mesh(geometry, new THREE.MeshPhongMaterial(0x202020)))
    });
  }
zhuber commented 6 years ago

Thanks for the helpful advice @nick-parker.

This is still a bit of a complicated process, with a lot of things that might be tricky or error prone for a large variety of users. I've taken this basic approach and created a package that streamlines the process and allows users to simply use a React Component with some props: https://www.npmjs.com/package/react-three-renderer-objects

Hopefully this helps people get 3D models and materials into their scene easier and more consistently.

toxicFork commented 6 years ago

Thank you so much @zhuber for the package!

hishammalik commented 5 years ago

this is not working anymore with latest version of react. Tested on react 16.4.1. ref on scene doesn't work and not able to get access to the threejs scene object. Please let me know if there is a way around.