How to use Three JS in React JS
React-three-fiber is a React renderer for three.jsInstalling react-three-fibernpm install three @react-three/fiber Create your first geometryimport { createRoot } from 'react-dom/client’import React, { useRef, useState } from 'react’import { Canvas, useFrame } from '@react-three/fiber’function Box(props) { // This reference gives us direct access to the THREE.Mesh object const ref = useRef() // Hold state for hovered and clicked events const [hovered, hover] = useState(false) const [clicked, click] = useState(false) // Subscribe this component to the render-loop, rotate the mesh every frame useFrame((state, delta) => (ref.current.rotation.x += delta)) // Return the view, these are regular Threejs elements expressed in JSX return ( <mesh {…props} ref={ref} scale={clicked ? 1.5 : 1} onClick={(event) => click(!clicked)} onPointerOver={(event) => hover(true)} onPointerOut={(event) => hover(false)}> <boxGeometry args={[1, 1, 1]} /> <meshStandardMaterial color={hovered ? ‘hotpink’ : ‘orange’} /> )}createRoot(document.getElementById(‘root’)).render( <pointLight position={[10, 10, 10]} /> <Box position={[-1.2, 0, 0]} /> <Box position={[1.2, 0, 0]} /> ,)
三个JS例子:5.三个JS动画关键帧
最新推荐文章于 2024-07-11 18:23:29 发布
文章介绍了如何在React应用中使用react-three-fiber库来渲染ThreeJS场景。通过创建geometry、设置mesh属性,以及利用useFrame更新动画,创建交互式的3D方块,并添加了鼠标悬停和点击事件处理。
摘要由CSDN通过智能技术生成