![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Creating 3D Globe using React-three-fiber
In this article, you will learn how to create a globe using react-threefiber. We will first make a sphere and then map a whole Earth map on it. This is an interesting texture loader feature using which we canmake any image to wrap over a sphere as texture. So, let's get started!
Example
First, download important libraries −
npm i --save @react-three/fiber three
This library react-three/fiber will be used to add webGL renderer to the website and to connect threejs and React.
Download an image of Earth map and place it in the “src” folder. We have named the image file as "world-map.gif".
Add 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 earthImg from './world-map.gif' import "./App.css"; const Sphere=()=>{ const base=new THREE.TextureLoader().load(earthImg) const ref=useRef() useFrame(() => (ref.current.rotation.x=ref.current.rotation.y += 0.01)) <return( <mesh visible castShadow ref={ref}> <directionalLight intensity={0.5} /> <sphereGeometry attach="geometry" args={[2, 32, 32]} /> <meshBasicMaterial map={base} color="white" /> </mesh> ) } export default function App(){ return ( <Canvas> <ambientLight /> <Sphere/> </Canvas> ); };
Explanation
Here we first created a Sphere and loaded a texture. Then we wrapped the texture over the sphere.
<mesh> is used to make threeJS object, and inside it we made a box using SphereGeometry which is used to define size, shape and other structural things.
meshBasicMaterial which is use 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. Next, we created a Frame which is used to change the position of our mesh object or sphere. Then we added frame to reference and gave reference to mesh.
The Position argument simply positions the object. <AmbientLight> is used to make the colors visible. In its absence, <Sphere> will look whole black.
Output
It will produce the following output −