使用 React-three-fiber 建立 3D 文字
在本文中,我們將瞭解如何使用 **react-threefiber** 建立 3D 文字。我們首先會下載 JSON 格式的字型檔案,然後將其新增到我們的 Text Geometry 物件中。我們會新增軌道控制,這將允許在螢幕上移動文字並正確檢視 3D 文字。所以,讓我們開始吧。
示例
首先,下載重要的庫:
npm i --save @react-three/fiber three
這個庫 **react-three/fiber** 將用於向網站新增 WebGL 渲染器,以及連線 **threejs** 和 **React**。
現在安裝一個字型 JSON 檔案並將其放入 “src” 資料夾中。您可以從 Google Fonts 下載字型,然後前往 https://gero3.github.io/facetype.js/ 將其轉換為 JSON 格式。
在 **App.js** 中新增以下程式碼:
import React, { useEffect, useRef } from "react"; import { Canvas, useThree ,useLoader } from "@reactthree/fiber"; import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"; import * as THREE from "three"; import Roboto from "./Roboto_Regular.json" import "./App.css"; const CameraController = () => { const { camera, gl } = useThree(); useEffect( () => { const controls = new OrbitControls(camera, gl.domElement); controls.minDistance = 3; controls.maxDistance = 20; return () => { controls.dispose(); }; }, [camera, gl] ); return null; }; function Text3d(){ const font = new THREE.FontLoader().parse(Roboto); const textOptions = { font, size: 5, height: 1 }; return ( <mesh> <textGeometry attach='geometry' args={['three.js', text Options]} /> <meshStandardMaterial attach='material' color="hotpink" /> </mesh> ) } export default function App(){ return ( <Canvas> <CameraController/> <ambientLight /> <Text3d/> </Canvas> ); };
解釋
我們首先使用 **“Roboto”** 變數載入了 JSON 字型,然後在我們的函式內部,將其解析為字型並將其儲存在 “font” 常量中。
然後,我們在 **“textOptions”** 中設定其樣式和其他方面。接下來,我們簡單地建立了 **textGeometry** 並傳遞了 **args**,並且 **material** 物件用於應用樣式。
輸出
它將產生以下輸出:
廣告