R3F(React Three Fiber)经验篇

2024-02-25 16:28

本文主要是介绍R3F(React Three Fiber)经验篇,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

之前一直在做ThreeJS方向,整理了两篇R3F(React Three Fiber)的文档,这是经验篇,如果您的业务场景需要使用R3F,可以参考一下这个文档。下面是目录,按照需求自取。

基础篇 ⬇️

R3F(React Three Fiber)基础篇

React Three Fiber Development Experience

文章目录

  • React Three Fiber Development Experience
    • 一、Asset Website
    • 二、Libraries
      • 1. three-stdlib
    • 三、Usage
      • 1. 动画周期震荡
      • 2. 内部摄像机
      • 3. camera far和fov的区别
      • 4. Bvh
      • 5. leva
        • 枚举类型
      • 6. 一个镜面反射的球
      • 7. 在场景里居中
      • 8. 自带环境
      • 9. 给一个物体添加一个可移动的,带有坐标系的控制器
      • 10. Float
      • 11. Mask
      • 12. 更改GLTF模型颜色
      • 13. Better TypeScript Support for useGLTF
      • 14. Sparkles
      • 15. 随机色

一、Asset Website

https://gltf.pmnd.rs/:GLTF -> React Three Fiber

https://polyhaven.com/ : Assert Website

二、Libraries

1. three-stdlib

Stand-alone version of threejs/examples/jsm written in Typescript & built for ESM & CJS.

可以为 threejs中 不支持 TS 的 代码提供TS支持

install

npm install three-stdlib

usage

// Export collection
import * as STDLIB from 'three-stdlib'
// Flatbundle
import { OrbitControls, ... } from 'three-stdlib'

三、Usage

1. 动画周期震荡

useFrame((state) => (textRef.current.position.x = Math.sin(state.clock.elapsedTime) * 2))

完整例子:

const Cube: FC = () => {const textRef = useRef<Mesh>(null!)useFrame((state) => (textRef.current.position.x = Math.sin(state.clock.elapsedTime) * 2))return (<mesh><boxGeometry /><meshStandardMaterial><RenderTexture attach="map" anisotropy={16}><PerspectiveCamera makeDefault manual aspect={1} position={[0, 0, 5]} /><color attach="background" args={['orange']} /><Text fontSize={4} color={'#555'} ref={textRef}>hello</Text></RenderTexture></meshStandardMaterial></mesh>)
}

2. 内部摄像机

关键属性:makeDefault manual

TSX:<PerspectiveCamera makeDefault manual aspect={1} position={[0, 0, 5]} />

例子见动画周期震荡d艾玛

3. camera far和fov的区别

<Canvas shadows camera={{ position: [0, 0, 3], fov: 10 }}>

在Three.js中,farfov是两种不同的概念,都与渲染3D场景时的视觉效果有关,但是它们的作用是不同的。

  1. far:这个参数是在设置相机的裁剪面时使用的,表示相机能看到的最远距离。当一个物体离相机的距离超过这个值时,这个物体就不会被渲染出来。换句话说,far定义了你的视野的"深度"。
  2. fov:这是相机的视场角度(Field of View),以度为单位。它定义了相机视野的"宽度",即相机能够看到的角度大小。在Three.js中,这个值默认是50度,但可以根据需要进行调整。

所以,farfov在控制渲染效果上有不同的作用:far控制的是视野的深度,而fov控制的是视野的宽度。在实际应用中,你需要根据你的需求来调整这两个参数。

far和设置position z轴的效果是一样的。

4. Bvh

参考:https://github.com/pmndrs/drei#bvh

使用Bvh包裹的组件,性能会更好,原因不明

<Canvas><Bvh firstHitOnly><Scene /></Bvh>
</Canvas>

5. leva

一种GUI库,可以用作参数调试或简易设置界面

useControls最终的配置项会合并到一起。

具体用法参考一、RTF Debugger

import { useControls } from 'leva'
function CSphere() {const { roughness } = useControls({ roughness: { value: 1, min: 0, max: 1 } })return (<Center top><mesh castShadow><sphereGeometry args={[0.75, 64, 64]} /><meshStandardMaterial metalness={1} roughness={roughness} /></mesh></Center>)
}

img

枚举类型
const { model } = useControls({ model: { value: 'Beech', options: Object.keys(MODELS) } })

6. 一个镜面反射的球

关键参数:

metalness:数值为 1 反光率最大,距离1越大,镜面反射转为漫反射效果越明显。

roughness:有点抛光那个意思,数值越大,镜面效果越明显

<mesh castShadow><sphereGeometry args={[0.75, 64, 64]} /><meshStandardMaterial metalness={1} roughness={roughness} />
</mesh>

7. 在场景里居中

<Center top><mesh castShadow><sphereGeometry args={[0.75, 64, 64]} /><meshStandardMaterial metalness={1} roughness={roughness} /></mesh>
</Center>

8. 自带环境

<Environment preset={preset} background blur={blur} />
preset?: PresetsType;
background?: boolean | 'only';
export declare const presetsObj: {apartment: string;city: string;dawn: string;forest: string;lobby: string;night: string;park: string;studio: string;sunset: string;warehouse: string;
};
export type PresetsType = keyof typeof presetsObj;

background为only时,不反射环境光

9. 给一个物体添加一个可移动的,带有坐标系的控制器

<PivotControls offset={[0, 0, 1]} activeAxes={[true, true, false]} disableRotations depthTest={true}><CFrame position={[0, 0, 1]} /><Mask id={1} position={[0, 0, 0.95]}><circleGeometry args={[0.8, 64]} /></Mask>
</PivotControls>

10. Float

让内容上下浮动

<Floatspeed={1} // Animation speed, defaults to 1rotationIntensity={1} // XYZ rotation intensity, defaults to 1floatIntensity={1} // Up/down float intensity, works like a multiplier with floatingRange,defaults to 1floatingRange={[1, 10]} // Range of y-axis values the object will float within, defaults to [-0.1,0.1]
><mesh />
</Float>

11. Mask

可以用来遮罩效果

CAtom 定义需要遮挡的物体

const CAtom: FC<{ invert?: boolean } & MeshProps> = ({ invert, ...props }) => {// 定义 stencil,1为id,false为将物体遮挡(隐藏)const stencil = useMask(1, false)const { nodes } = useGLTF('/glb/react-transformed.glb') as unknown as { nodes: Record<string, any> }const gltf = useGLTF('/glb/react-transformed.glb')return (<meshcastShadow={true}receiveShadow={true}geometry={nodes.atom.geometry}dispose={null}{...props}><meshPhongMaterial color="#33BBFF" {...stencil} /></mesh>)
}

在另一个组件,用Mask 投影被遮挡的物体的图像

<PivotControls offset={[0, 0, 1]} activeAxes={[true, true, false]} disableRotations depthTest={true}><CFrame position={[0, 0, 1]} />{ // 这里和id和之前那个Mask的id对应 }<Mask id={1} position={[0, 0, 0.95]}><circleGeometry args={[0.8, 64]} /></Mask>
</PivotControls>
<Bounds fit clip observe><Float floatIntensity={4} rotationIntensity={0} speed={4}><CAtom invert={invert} scale={1.5} /></Float>
</Bounds>

12. 更改GLTF模型颜色

参考案例:https://codesandbox.io/s/re-using-gltfs-forked-wpzjcg?file=/src/Shoe.js

声明式写法

const MShoe: FC<{ color: string } & Record<string, any>> = ({ color, ...props }) => {const gltf = useGLTF('glb/shoe.gltf');const { nodes, materials } = gltf as unknown as {nodes: Record<string, any>materials: Record<string, any>};// 建立nodes和materials映射关系const nodeArr = Object.entries(nodes).filter(([key, value], index) => index > 1);const materialArr = Object.values(materials)const changeColorNode = 'shoe_1';// 重新构建组合 Meshreturn (<group {...props} dispose={null}>{ nodeArr.map(([key, node], index) => (<meshkey={key}castShadow={true}receiveShadow={true}geometry={node.geometry}material={index !== 1 ? materialArr[index] : undefined}material-envMapIntensity={0.8}>{key === changeColorNode &&<meshStandardMaterial{...materials.mesh}color={color}envMapIntensity={0.8}normalMap-encoding={LinearEncoding}/>}</mesh>))}</group>)
}

编程式写法

	const MShoe2: FC<ModelProps> = (props) => {const gltf = useGLTF('glb/shoe.gltf')const { scene } = gltf;const { materials } = gltf as unknown as Record<string, any>;const ref = useRef<Group>(null!);useEffect(() => {ref.current.traverse(child => {if(child.name === 'shoe_1' && (child as any).isMesh) {(child as any).material = new MeshStandardMaterial({...materials.mesh,color: 0xff6666,envMapIntensity: 0.8,});}})}, [materials]);return <primitive object={scene} {...props} ref={ref}/>
}

13. Better TypeScript Support for useGLTF

Refer to the Libraries chapter for three-stdlib

Declare

declare type C_GLTF = import('three-stdlib').GLTF & {nodes: Record<string, import("three").Mesh>;materials: Record<string, import("three").MeshStandardMaterial>;
};

Usage

const { nodes, materials } = useGLTF('/cyberpunk.glb', true) as C_GLTF;

14. Sparkles

繁星效果,Floating, glowing particles(发光粒子).

<Sparklessize={ 6 }scale={ [ 4, 2, 6 ] }position-y={ 1 }speed={ 0.1 }
/>

15. 随机色

type TorusMesh = Mesh<TorusGeometry, MeshMatcapMaterial>const eventHandler = (event: ThreeEvent<MouseEvent>) => {event.stopPropagation();const mesh= event.eventObject as TorusMesh;const newMaterial = mesh.material.clone()newMaterial.color.set(`hsl(${Math.random() * 360}, 100%, 75%)`) // hsl colormesh.material = newMaterial;
}

这篇关于R3F(React Three Fiber)经验篇的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/746041

相关文章

SpringBoot返回文件让前端下载的几种方式

《SpringBoot返回文件让前端下载的几种方式》文章介绍了开发中文件下载的两种常见解决方案,并详细描述了通过后端进行下载的原理和步骤,包括一次性读取到内存和分块写入响应输出流两种方法,此外,还提供... 目录01 背景02 一次性读取到内存,通过响应输出流输出到前端02 将文件流通过循环写入到响应输出流

SpringBoot+Vue3整合SSE实现实时消息推送功能

《SpringBoot+Vue3整合SSE实现实时消息推送功能》在日常开发中,我们经常需要实现实时消息推送的功能,这篇文章将基于SpringBoot和Vue3来简单实现一个入门级的例子,下面小编就和大... 目录前言先大概介绍下SSE后端实现(SpringBoot)前端实现(vue3)1. 数据类型定义2.

前端Visual Studio Code安装配置教程之下载、汉化、常用组件及基本操作

《前端VisualStudioCode安装配置教程之下载、汉化、常用组件及基本操作》VisualStudioCode是微软推出的一个强大的代码编辑器,功能强大,操作简单便捷,还有着良好的用户界面,... 目录一、Visual Studio Code下载二、汉化三、常用组件1、Auto Rename Tag2

vite搭建vue3项目的搭建步骤

《vite搭建vue3项目的搭建步骤》本文主要介绍了vite搭建vue3项目的搭建步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录1.确保Nodejs环境2.使用vite-cli工具3.进入项目安装依赖1.确保Nodejs环境

Nginx搭建前端本地预览环境的完整步骤教学

《Nginx搭建前端本地预览环境的完整步骤教学》这篇文章主要为大家详细介绍了Nginx搭建前端本地预览环境的完整步骤教学,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录项目目录结构核心配置文件:nginx.conf脚本化操作:nginx.shnpm 脚本集成总结:对前端的意义很多

前端缓存策略的自解方案全解析

《前端缓存策略的自解方案全解析》缓存从来都是前端的一个痛点,很多前端搞不清楚缓存到底是何物,:本文主要介绍前端缓存的自解方案,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录一、为什么“清缓存”成了技术圈的梗二、先给缓存“把个脉”:浏览器到底缓存了谁?三、设计思路:把“发版”做成“自愈”四、代码

通过React实现页面的无限滚动效果

《通过React实现页面的无限滚动效果》今天我们来聊聊无限滚动这个现代Web开发中不可或缺的技术,无论你是刷微博、逛知乎还是看脚本,无限滚动都已经渗透到我们日常的浏览体验中,那么,如何优雅地实现它呢?... 目录1. 早期的解决方案2. 交叉观察者:IntersectionObserver2.1 Inter

Vue3视频播放组件 vue3-video-play使用方式

《Vue3视频播放组件vue3-video-play使用方式》vue3-video-play是Vue3的视频播放组件,基于原生video标签开发,支持MP4和HLS流,提供全局/局部引入方式,可监听... 目录一、安装二、全局引入三、局部引入四、基本使用五、事件监听六、播放 HLS 流七、更多功能总结在 v

JS纯前端实现浏览器语音播报、朗读功能的完整代码

《JS纯前端实现浏览器语音播报、朗读功能的完整代码》在现代互联网的发展中,语音技术正逐渐成为改变用户体验的重要一环,下面:本文主要介绍JS纯前端实现浏览器语音播报、朗读功能的相关资料,文中通过代码... 目录一、朗读单条文本:① 语音自选参数,按钮控制语音:② 效果图:二、朗读多条文本:① 语音有默认值:②

vue监听属性watch的用法及使用场景详解

《vue监听属性watch的用法及使用场景详解》watch是vue中常用的监听器,它主要用于侦听数据的变化,在数据发生变化的时候执行一些操作,:本文主要介绍vue监听属性watch的用法及使用场景... 目录1. 监听属性 watch2. 常规用法3. 监听对象和route变化4. 使用场景附Watch 的