如何将Threejs连接到React?

evg*_*kch 22 three.js reactjs

我使用React并使用画布.我想将画布更改为WebGL(Threejs库).如何将此库连接到React?

我有一些元素,例如

<div ref="threejs"></div>
Run Code Online (Sandbox Code Playgroud)

如何使它成为Threejs库调用的字段?PS:.我不想使用像react-threejs这样的扩展

Web*_*eed 70

以下是如何进行设置的示例(请参阅演示):

import React, { Component } from 'react'
import * as THREE from 'three'

class Scene extends Component {
  constructor(props) {
    super(props)

    this.start = this.start.bind(this)
    this.stop = this.stop.bind(this)
    this.animate = this.animate.bind(this)
  }

  componentDidMount() {
    const width = this.mount.clientWidth
    const height = this.mount.clientHeight

    const scene = new THREE.Scene()
    const camera = new THREE.PerspectiveCamera(
      75,
      width / height,
      0.1,
      1000
    )
    const renderer = new THREE.WebGLRenderer({ antialias: true })
    const geometry = new THREE.BoxGeometry(1, 1, 1)
    const material = new THREE.MeshBasicMaterial({ color: '#433F81' })
    const cube = new THREE.Mesh(geometry, material)

    camera.position.z = 4
    scene.add(cube)
    renderer.setClearColor('#000000')
    renderer.setSize(width, height)

    this.scene = scene
    this.camera = camera
    this.renderer = renderer
    this.material = material
    this.cube = cube

    this.mount.appendChild(this.renderer.domElement)
    this.start()
  }

  componentWillUnmount() {
    this.stop()
    this.mount.removeChild(this.renderer.domElement)
  }

  start() {
    if (!this.frameId) {
      this.frameId = requestAnimationFrame(this.animate)
    }
  }

  stop() {
    cancelAnimationFrame(this.frameId)
  }

  animate() {
    this.cube.rotation.x += 0.01
    this.cube.rotation.y += 0.01

    this.renderScene()
    this.frameId = window.requestAnimationFrame(this.animate)
  }

  renderScene() {
    this.renderer.render(this.scene, this.camera)
  }

  render() {
    return (
      <div
        style={{ width: '400px', height: '400px' }}
        ref={(mount) => { this.mount = mount }}
      />
    )
  }
}

export default Scene
Run Code Online (Sandbox Code Playgroud)

您可能还对全屏示例感兴趣(请参阅GitHub).

这是使用React Hooks而不是类的示例(注意:Hooks目前是实验性的).

  • 在搞清楚之后发现这一点,这应该更受欢迎! (3认同)

Mob*_*dde 7

我知道问题有点老,但如果有人还在寻找什么。你会尝试https://github.com/drcmda/react-three-fiber。他们的 github 上有一些片段和演示。

  • 与您使用 react-dom 而不是原始 dom createElement 和 innerHtml 的原因相同。您可以随意使用整个 React 生态系统,并且可以将场景图分解为反应组件。 (4认同)
  • 如果您愿意,可以浏览我最近的一些 Twitter 内容:https://twitter.com/0xca0a 您会看到很多展示 React+Three 的演示。特别是我一周前制作的游戏:https://twitter.com/0xca0a/status/1184586883520761856。React 不是 html,jsx 只是一个 dsl: &lt;mesh/&gt; 实际上与 new THREE.Mesh(...) 相同,但这不是重点,它现在是响应式和托管的,这就是为什么世界上所有的差异。 (4认同)
  • @hpalu我有点好奇你什么时候以及为什么想要这样做?我还没有看到一个令人信服的例子来说明为什么这将是一个好主意,无论上下文游戏、时髦的网站、GUI 元素等如何。并不是一切都更好,只是因为你可以在一些伪 html(如标记方案)中做到这一点...... (3认同)
  • 为什么我应该使用“react-three-fiber”而不是“three”? (2认同)

小智 3

您可以使用反应三纤维

npm install three @react-three/fiber
Run Code Online (Sandbox Code Playgroud)

用法

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 (<React3
      mainCamera="camera" // this points to the perspectiveCamera which has the name set to "camera" below
      width={width}
      height={height}

      onAnimate={this._onAnimate}
    >
      <scene>
        <perspectiveCamera
          name="camera"
          fov={75}
          aspect={width / height}
          near={0.1}
          far={1000}
          position={this.cameraPosition}
        />
        <mesh
          rotation={this.state.cubeRotation}
        >
          <boxGeometry
            width={1}
            height={1}
            depth={1}
          />
          <meshBasicMaterial
            color={0x00ff00}
          />
        </mesh>
      </scene>
    </React3>);
  }
}
ReactDOM.render(<Simple/>, document.body);
Run Code Online (Sandbox Code Playgroud)

  • “我不想使用像react-twojs这样的扩展” (17认同)