在 React 中使用 react-three-fiber 建立座標軸輔助線


當應用任何軌道控制時,座標軸輔助線用於顯示三維圖形的方向。座標軸利用座標幾何的概念來展示如何建立形狀併為縮放、旋轉、滑動等操作建立軌道。在開發 3D 環境時,它們非常有用。

示例

首先下載 **react-three-fiber** 包 -

npm i --save @react-three/fiber three

**threejs** 和 **react-three/fiber** 將用於向網站新增 WebGL 渲染器。Three-fiber 將用於連線 **threejs** 和 **React**。

我們首先建立一個長方體和一個軌道控制,以便更好地檢視。

在 **App.js** 中新增以下程式碼行 -

import React, { useEffect } from "react";
import { Canvas, useThree } from "@react-three/fiber";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import * as THREE from "three";

const CameraController = () => {
   const { camera, gl } = useThree();
   useEffect(() => {
      const controls = new OrbitControls(camera, gl.domElement);
      return () => {
         controls.dispose();
      };
   }, [camera, gl]);
   return null;
};
export default function App() {
   return (
      <Canvas>
         <CameraController />
         <ambientLight />
         //here axes helper is applied
         <primitive object={new THREE.AxesHelper(10)} />
         <mesh>
            <boxGeometry attach="geometry" args={[5, 5, 5]} />
            <meshBasicMaterial attach="material" color="lightblue" />
         </mesh>
      </Canvas>
   );
}

解釋

我們只是建立了一個軌道控制和一個立方體。

座標軸輔助線用於顯示 3D 物件的方向。我們只是建立了一個立方體幾何體,並使用 **meshBasicMaterial** 進行樣式設定。

輸出

它將產生以下輸出 -

綠色、藍色和紅色燈光用於顯示方向。

更新於: 2021年9月28日

2K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.