How to connect Threejs to React?

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

    Here is an example of how to set this up (see demo):

    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 (
          
    { this.mount = mount }} /> ) } } export default Scene

    You might also be interested in a full screen example (see GitHub).

    Here's an example using React Hooks instead of a class.

提交回复
热议问题