
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
Create 3D Metal Texture Box in React using React Three Fiber
In this article, we will see how to make a metallic texture cubic box in React JS using React-Three-Fiber package. First, we will download a metallic photo and then we will apply it over all the surfaces of a cube. Cubes are basic shapes but we can make them look attractive by wrapping an image over its surfaces. So, let's get start.
Example
First download and install the following packages −
npm i --save @react-three/fiber three
threejs and react-three/fiber will be used to add webGL renderer to the website and three-fiber will be used to connect threejs and React.
Now let's download a metallic image and put it inside the “src” folder. I have this image and I have named it "download2.jpg −
Next, insert the following lines of code in App.js −
import React, { useRef } from "react"; import { Canvas, useFrame, useLoader } from "@reactthree/fiber"; import * as THREE from "three"; import metal from "./download2.jpg"; import "./App.css"; function Box(props) { const mesh = useRef(); useFrame(() => (mesh.current.rotation.x = mesh.current.rotation.y += 0.01)); const base = new THREE.TextureLoader().load(metal); return ( <mesh {...props} ref={mesh}> <boxGeometry args={[3, 3, 3]} /> <meshBasicMaterial attach="material" color={"lightblue"} map={base} /> </mesh> ); } export default function App() { return ( <Canvas> <ambientLight /> <Box /> </Canvas> ); }
Explanation
Here, we created a <Box> object.
Then, we imported our image as “metal” variable.
Then, we converted that metal image to texture and stored it in “base” constant.
Next, inside meshBasicMaterial, we applied that texture using “map” function.
We also added rotation to our cube to make it look more beautiful. We used useFramer to add rotation functionality.
Output
On execution, it will produce the following output −