在小程序中使用 React Three Fiber 快速搭建 3D 场景

示例展示

示例1 示例2示例3

什么是 React Three Fiber(R3F)?

React Three Fiber,简称 R3F,是一个基于 three.js 的 React 渲染器。它将 WebGL 场景以 React 组件的形式封装,使得开发者可以像写 React 页面一样去构建和组织 3D 场景。

如果你对 R3F 尚不了解,可以参考 官方文档。本篇文章将重点介绍如何在小程序中集成并运行 R3F。

如何在小程序中使用 three.js?

如果你尚未了解如何在小程序中使用 three.js,推荐先阅读我之前的文章:《如何在小程序中优雅地使用 three.js》,为本篇打下基础。


相关工具与依赖

为了在小程序中支持 WebGL 渲染和 React 运行时,我们将使用以下工具:


快速启动示例

推荐直接使用模板仓库进行体验,顶部所有的 Demo 都可以在下方模板找到:

npx degit minisheeep/threejs-miniprogram-template#uni-ts-r3f my-project
cd my-project
pnpm install
pnpm dev:open

手动集成指南

如果你希望在现有小程序项目中手动集成 R3F,可按如下步骤操作。
当前支持基于 viterollup 的构建系统,未来将支持更多环境。

第一步:添加 .npmrc 配置

由于部分依赖未发布至 npm 官方仓库,需手动指定私有源:

@minisheep:registry=https://npm.minisheep.cn

第二步:安装依赖

pnpm i @minisheep/mini-program-polyfill-core @minisheep/three-platform-adapter @minisheep/platform-adapter-integration react @react-three/fiber @react-three/drei three
pnpm i @vitejs/plugin-react -D

第三步:配置 vite.config.js

import { defineConfig } from 'vite';
import threePlatformAdapter from '@minisheep/three-platform-adapter/plugin';
import react from '@vitejs/plugin-react';
// import { supportR3fInUni } from '@minisheep/platform-adapter-integration/r3f/plugin'; // 如果你使用 uni-app

export default defineConfig({
  plugins: [
    threePlatformAdapter(),
    react(),
    // supportR3fInUni(),
  ],
});

编写基础 3D 场景

scenes/baseScene.jsx

import { Canvas } from '@react-three/fiber';

export function createBaseScene(eventSource) {
  return (
    <Canvas eventSource={eventSource}>
      <mesh>
        <torusGeometry args={[1, 0.5, 16, 32]} />
        <meshBasicMaterial color="orange" />
      </mesh>
      <ambientLight intensity={1} />
    </Canvas>
  );
}

小程序页面配置

pages/scene.wxml

<canvas
  type="webgl2"
  id="r3f_demo"
  bindtouchstart="defaultHandler"
  bindtouchmove="defaultHandler"
  bindtouchcancel="defaultHandler"
  bindtouchend="defaultHandler"
  bindtap="defaultHandler"
/>

pages/scene.js

import { adapter } from "@minisheep/three-platform-adapter";
import { createRoot } from "@minisheep/platform-adapter-integration/r3f";
import { createBaseScene } from "../scenes/baseScene";

Page({
  app: null,
  onLoad(query) {
    this.sceneId = query?.scene ?? 'base';
  },
  async onReady() {
    const result = await adapter.useCanvas('#r3f_demo', this);
    this.defaultHandler = result.eventHandler;
    this.app = createRoot(result.canvas).render(createBaseScene(result.canvas));
  },
  defaultHandler(e) {},
  onUnload() {
    this.app?.unmount();
  }
});

运行后你将看到如下效果:

在这里插入图片描述

结语

借助 R3F 以及 @minisheep 提供的完整工具链,你可以在小程序中高效地构建出功能丰富、表现力强的 3D 场景,充分结合 React 的声明式开发方式和 three.js 的图形渲染能力。

本文仅展示了一个基础示例,实际开发中你还可能会面临诸如分包大小限制、资源管理等更多挑战。由于篇幅所限,这些内容在此不做展开,欢迎访问 官网 获取更详尽的信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值