
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Make a Ring in React Using React Three Fiber
In this article, we will see how to use the react-three-fiber package in React to make a ring which will rotate. Three.js is a cross-browser JavaScript library and application programming interface used to create and display animated 3D computer graphics in a web browser using WebGL
Example
First, download important libraries −
npm i --save @react-three/fiber three
threejs and react-three/fiber will be used to add webGL renderer to the website.
Add the following lines of code in index.css −
* { box-sizing: border-box; } html,body,#root{ width: 100%; height: 100%; margin: 0; padding: 0; }
This default styling will make the Canvas match the parent.
Add the following lines of code in App.js −
import React, { useRef } from "react"; import { Canvas, useFrame } from "@react-three/fiber"; function Ring() { const ref = useRef(null); useFrame(() => (ref.current.rotation.x = ref.current.rotation.y += 0.01)); return ( <mesh visible position={[0, 0, 0]} rotation={[0, 0, 0]} castShadow ref={ref}> <ringBufferGeometry args={[1, 4, 32]} /> <meshBasicMaterial attach="material" color="hotpink" /> </mesh> ); } export default function App() { return ( <Canvas> <ambientLight /> <Ring /> </Canvas> ); }
Explanation
Ring takes 3 arguments − inner radius, outer radius and the third parameter is the theta segment which decides how round will be the ring.
<mesh is used to make the threeJS object, and inside it, we made a box using RingGeometry which is used to define the size, shape and other structural things.
We used the meshStandardMaterial to design our geometrical structure.
<mesh is used to combine the structure and the design together. We created a functional component inside which we made a reference. Then we created a Frame which is used to change the position of our mesh object or ring.
Then we added the frame to reference and gave reference to the mesh.
We used the position argument to simply position the object.
<AmbientLight> is used to make the color visible; in its absence, the <Ring> will look completely black.
Output
It will produce the following output −