Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Making a wobbling cube in React using react-three-fiber
In this article, we will see how to make a wobbling cube in React, which will be wobbling in a loop and spinning at same time. We will first make a cube and then add the wobbling effect. We can also add a feature to make the cube wobble on hovering. So, let's get started.
Example
First download the react-three-fiber package −
npm i --save @react-three/fiber npm i --save @react-three/drei npm i --save three
threejs and react-three/fiber will be used to add webGL renderer to the website. react-three/fiber will be used to connect threejs and React. drei is used to add wobblingMesh.
Add the following lines of code in App.js −
import React, { useRef } from "react";
import { Canvas, useFrame } from "@react-three/fiber";
import { MeshWobbleMaterial } from "@react-three/drei";
function Box(props) {
const mesh = useRef();
useFrame(() => (mesh.current.rotation.x = mesh.current.rotation.y += 0.01));
return (
);
}
export default function App() {
return (
);
}
Explanation
Here we first created a BoxGeometry object. Then in the material object we provided MeshWobbleMaterial which we imported from drei. The code is quite self-explanatory; we did some basic lighting and positioned the object.
Output
On execution, it will produce the following output −
