gpt4 book ai didi

reactjs - 如何将Threejs连接到React?

转载 作者:行者123 更新时间:2023-12-03 13:02:48 25 4
gpt4 key购买 nike

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

我有一些元素,例如

<div ref="threejs"></div>

如何使其成为Threejs库调用的字段?我不想使用像 react-thirdjs 这样的扩展。

最佳答案

以下是如何设置的示例 ( 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 (
<div
style={{ width: '400px', height: '400px' }}
ref={(mount) => { this.mount = mount }}
/>
)
}
}

export default Scene

您可能还对 full screen example 感兴趣(参见GitHub)。

Here's an example using React Hooks而不是一个类。

关于reactjs - 如何将Threejs连接到React?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41248287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com