Advertisement
bbcqx

Untitled

Apr 7th, 2023
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. Here's a simple React component that utilizes TypeScript, Next.js, and Three.js to display a 3D model in GLB format. This component allows users to rotate and zoom in and out of the model:
  2.  
  3. Install the necessary dependencies:
  4. bash
  5. Copy code
  6. npm install three @types/three next-three-fiber
  7. Create a new file called ModelViewer.tsx in your Next.js components folder and paste the following code:
  8. typescript
  9. Copy code
  10. import React, { useRef } from 'react';
  11. import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
  12. import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
  13. import { Canvas, useFrame, useLoader, useThree, extend } from '@react-three/fiber';
  14.  
  15. extend({ OrbitControls });
  16.  
  17. type OrbitControlsProps = JSX.IntrinsicElements['orbitControls'] & {
  18. children: React.ReactNode;
  19. };
  20.  
  21. const Controls = (props: OrbitControlsProps) => {
  22. const { gl, camera } = useThree();
  23. const controlsRef = useRef<OrbitControls>();
  24. useFrame(() => controlsRef.current?.update());
  25. return <orbitControls ref={controlsRef} args={[camera, gl.domElement]} {...props} />;
  26. };
  27.  
  28. type ModelProps = {
  29. url: string;
  30. };
  31.  
  32. const Model: React.FC<ModelProps> = ({ url }) => {
  33. const gltf = useLoader(GLTFLoader, url);
  34. return <primitive object={gltf.scene} dispose={null} />;
  35. };
  36.  
  37. type ModelViewerProps = {
  38. modelUrl: string;
  39. };
  40.  
  41. const ModelViewer: React.FC<ModelViewerProps> = ({ modelUrl }) => {
  42. return (
  43. <Canvas style={{ width: '100%', height: '100%' }}>
  44. <ambientLight intensity={0.5} />
  45. <directionalLight position={[0, 10, 5]} intensity={1} />
  46. <Model url={modelUrl} />
  47. <Controls />
  48. </Canvas>
  49. );
  50. };
  51.  
  52. export default ModelViewer;
  53. Import and use the ModelViewer component in your Next.js page:
  54. typescript
  55. Copy code
  56. import React from 'react';
  57. import ModelViewer from '../components/ModelViewer';
  58.  
  59. const HomePage: React.FC = () => {
  60. return (
  61. <div style={{ width: '100vw', height: '100vh' }}>
  62. <ModelViewer modelUrl="/path/to/your/model.glb" />
  63. </div>
  64. );
  65. };
  66.  
  67. export default HomePage;
  68. Make sure to replace "/path/to/your/model.glb" with the actual path to your 3D model in GLB format. This component will render the 3D model and allow users to rotate and zoom in and out of the model using mouse controls.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement