How to connect Threejs to React?

后端 未结 5 1063
[愿得一人]
[愿得一人] 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:23

    You can using library https://github.com/toxicFork/react-three-renderer

    Installation

    npm install --save react@15.5.3 react-dom@15.5.3 three@0.84.0
    npm install --save react-three-renderer
    

    Usage

    import React from 'react';
    import React3 from 'react-three-renderer';
    import * as THREE from 'three';
    import ReactDOM from 'react-dom';
    
    class Simple extends React.Component {
      constructor(props, context) {
        super(props, context);
    
        // construct the position vector here, because if we use 'new' within render,
        // React will think that things have changed when they have not.
        this.cameraPosition = new THREE.Vector3(0, 0, 5);
    
        this.state = {
          cubeRotation: new THREE.Euler(),
        };
    
        this._onAnimate = () => {
          // we will get this callback every frame
    
          // pretend cubeRotation is immutable.
          // this helps with updates and pure rendering.
          // React will be sure that the rotation has now updated.
          this.setState({
            cubeRotation: new THREE.Euler(
              this.state.cubeRotation.x + 0.1,
              this.state.cubeRotation.y + 0.1,
              0
            ),
          });
        };
      }
    
      render() {
        const width = window.innerWidth; // canvas width
        const height = window.innerHeight; // canvas height
        return (
          
            
            
              
              
            
          
        );
      }
    }
    ReactDOM.render(, document.body);
    

提交回复
热议问题