Create a 3D planet viewer with React

Tiempo de lectura: 2 minutos

Here’s a step-by-step tutorial to create the React component “QuantumUniverseExplorer,” allowing you to explore a 3D universe interactively. This tutorial uses WebGL and Three.js for visualization. Let’s dive into the quantum cosmos!

Step 1: Project Setup :rocket:

Create a new React project with Create React App:

    npx create-react-app universe-explorer
    cd universe-explorer

Step 2: Library Installation :books:

Install the Three.js and React Three Fiber libraries:

    npm install three @react-three/fiber @react-three/drei

Step 3: QuantumUniverseExplorer Component :milky_way:

Create a new component named QuantumUniverseExplorer.js in the src folder:

// src/QuantumUniverseExplorer.js
import React, { useEffect } from 'react';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { extend } from '@react-three/fiber';
import * as THREE from 'three';  // Agregamos esta línea

extend({ OrbitControls });  // Agregamos esta línea

const QuantumUniverseExplorer = () => {
    useEffect(() => {
        // Configuración del escenario
        const scene = new THREE.Scene();
        const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        const renderer = new THREE.WebGLRenderer();
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.getElementById('universe-container').appendChild(renderer.domElement);

        // Añadir planetas
        const geometry = new THREE.SphereGeometry(1, 32, 32);
        const material = new THREE.MeshBasicMaterial({ color: 0xffffff, wireframe: true });
        const planet = new THREE.Mesh(geometry, material);
        scene.add(planet);

        // Añadir estrellas de fondo
        const starsGeometry = new THREE.BufferGeometry();
        const starsMaterial = new THREE.PointsMaterial({ color: 0xFFFFFF, size: 0.1 });

        const starsVertices = [];
        for (let i = 0; i < 5000; i++) {
            const x = (Math.random() - 0.5) * 2000;
            const y = (Math.random() - 0.5) * 2000;
            const z = (Math.random() - 0.5) * 2000;
            starsVertices.push(x, y, z);
        }

        starsGeometry.setAttribute('position', new THREE.Float32BufferAttribute(starsVertices, 3));
        const stars = new THREE.Points(starsGeometry, starsMaterial);
        scene.add(stars);

        // Configurar controles de órbita
        const controls = new OrbitControls(camera, renderer.domElement);
        controls.enableDamping = true;
        controls.dampingFactor = 0.25;
        controls.enableZoom = false;

        // Configurar cámara
        camera.position.z = 5;

        // Animación del universo
        const animate = () => {
            requestAnimationFrame(animate);
            planet.rotation.x += 0.005;
            planet.rotation.y += 0.005;
            controls.update();
            renderer.render(scene, camera);
        };

        animate();

        // Limpiar recursos en la salida
        return () => {
            scene.remove(planet);
            scene.remove(stars);
            renderer.dispose();
        };
    }, []);

    return <div id="universe-container" className="universe-container"></div>;
};

export default QuantumUniverseExplorer;

Step 4: QuantumUniverseExplorer.css Styling :artist_palette:

Create a file named QuantumUniverseExplorer.css in the same folder as your component:

    /* src/QuantumUniverseExplorer.css */
    .universe-container {
      width: 100%;
      height: 100vh;
      overflow: hidden;
    }

Step 5: Integration in App.js :rocket:

Modify your App.js file to include QuantumUniverseExplorer:

// src/App.js
import React from 'react';
import QuantumUniverseExplorer from './QuantumUniverseExplorer';

function App() {
  return (
    <div>
      <h1>¡Explorador Cuántico del Universo!</h1>
      <QuantumUniverseExplorer />
    </div>
  );
}

export default App;

Step 6: Test Your Quantum Explorer :rocket:

Run your application with the magic command:

    npm start

Open your browser and go to http://localhost:3000. Get ready to explore the 3D universe!

Leave a Comment