How to connect Threejs to React?

后端 未结 5 1060
[愿得一人]
[愿得一人] 2020-12-07 16:39

I work with React and use a canvas. I want to change the canvas to WebGL (Threejs library). How to connect this library to React?

I have some element, e.g.

5条回答
  •  清歌不尽
    2020-12-07 17:17

    I have converted the first example of three.js to React thing. Hope this is helpful import React from 'react'; import './App.css'; import * as THREE from 'three';

    class App extends React.Component{
      constructor(props){
        super(props)
        this.scene = new THREE.Scene();
        this.camera = new THREE.PerspectiveCamera(75,
          window.innerWidth / window.innerHeight,
          0.1,
          1000
          );
        this.renderer = new THREE.WebGL1Renderer();
            this.renderer.setSize( window.innerWidth, window.innerHeight );
        this.geometry = new THREE.BoxGeometry();
        this.material = new THREE.MeshBasicMaterial( { color: 0x32a852});
            this.cube = new THREE.Mesh( this.geometry, this.material)
      }
      animate = () => {
        requestAnimationFrame(this.animate)
        this.cube.rotation.x += 0.01;
        this.cube.rotation.y += 0.01;
        this.renderer.render(this.scene, this.camera);
        
      }
      componentDidMount() {
            document.body.appendChild( this.renderer.domElement );
            this.scene.add( this.cube );
            this.camera.position.z = 5;
            this.animate()
        }
      render(){
        return(
          
          
        );
      }
    }
    
    export default App;
    

    So the idea is that the three components can be broken down to constructor, function of animate and componentdidmount. I believe this.varname can be place anywhere. I felt constructor was a good place. This way other examples can be set as well.

提交回复
热议问题