Create Immersive 3D Earth with Three.js: Interactive WebGL
Add to your RSS feed23 January 20254 min readTable of Contents
In modern web development, visual interaction is key to capturing user attention. Three.js, as one of the most powerful WebGL libraries, makes complex 3D visualization accessible. This article will detail how to create an interactive 3D earth display using Three.js.
Preparation: Technologies and Resources
Technology Stack
Required Resources
High-resolution earth texture
1. Project Initialization
Quick project setup with Vite:
1 npm create vite@latest earth-3d -- --template vanilla2 cd earth-3d3 npm install three
Change the index.html
file to include the main js file:
1 <!DOCTYPE html>2 <html lang="en">3 <head>4 <meta charset="UTF-8" />5 <link6 rel="icon"7 type="image/svg+xml"8 href="/vite.svg" />9 <meta10 name="viewport"11 content="width=device-width, initial-scale=1.0" />12 <title>3D Earth</title>13 </head>14 <body>15 <script16 type="module"17 src="/src/main.js"></script>18 </body>19 </html>
2. Create a 3D Scene
In the main.js
file, set up the Three.js scene:
1 import './style.css';2 import * as THREE from 'three';34 // Create the 3D scene5 const scene = new THREE.Scene();67 // Get canvas element (optional in this example)8 const canvas = document.getElementById('webglcanvas');910 // Create perspective camera11 const camera = new THREE.PerspectiveCamera(12 75, // Field of View (FOV)13 window.innerWidth / window.innerHeight, // Aspect Ratio14 0.1, // Near clipping plane15 1000 // Far clipping plane16 );17 camera.position.z = 500; // Position camera away from the scene1819 // Create WebGL renderer20 const renderer = new THREE.WebGLRenderer();21 renderer.setSize(window.innerWidth, window.innerHeight);22 document.body.appendChild(renderer.domElement);2324 // Create a group to manage 3D objects25 const group = new THREE.Group();26 scene.add(group);2728 // Mouse position tracking variables29 let mouseX = 0, mouseY = 0;3031 // Texture loader for earth image32 const loader = new THREE.TextureLoader();33 loader.load('3d.png', function (texture) {34 // Create sphere geometry35 const geometry = new THREE.SphereGeometry(200, 20, 20);3637 // Create material with loaded texture38 const material = new THREE.MeshBasicMaterial({39 map: texture40 });4142 // Create mesh by combining geometry and material43 const mesh = new THREE.Mesh(geometry, material);44 group.add(mesh);4546 // Add mouse move event listener47 document.addEventListener('mousemove', onDocumentMouseMove, false);48 });4950 // Mouse move handler51 function onDocumentMouseMove(event) {52 // Normalize mouse coordinates53 mouseX = (event.clientX - 0.5);54 mouseY = (event.clientY - 0.5);55 }5657 // Window resize handler58 function onWindowResize() {59 // Update camera aspect ratio60 camera.aspect = window.innerWidth / window.innerHeight;61 camera.updateProjectionMatrix();6263 // Resize renderer64 renderer.setSize(window.innerWidth, window.innerHeight);65 }6667 // Render and animation function68 function render() {69 // Smoothly move camera based on mouse position70 camera.position.x += (mouseX - camera.position.x) * 0.05;71 camera.position.y += (mouseY - camera.position.y) * 0.05;7273 // Ensure camera looks at the scene center74 camera.lookAt(scene.position);7576 // Rotate earth slowly77 group.rotation.y += 0.0005;78 group.rotation.x += 0.00001;7980 // Render the scene81 renderer.render(scene, camera);82 }8384 // Animation loop85 function animate() {86 requestAnimationFrame(animate);87 render();88 }8990 // Start the animation91 renderer.setAnimationLoop(animate);
Understanding the Code: A Line-by-Line Breakdown
1. Scene Setup
1 const scene = new THREE.Scene();
This line creates the fundamental 3D container. Think of it as a digital stage where all your 3D objects will perform.
2. Camera Configuration
1 const camera = new THREE.PerspectiveCamera(2 75, // Field of View (FOV)3 window.innerWidth / window.innerHeight, // Aspect Ratio4 0.1, // Near clipping plane5 1000 // Far clipping plane6 );
The camera mimics human vision:
- 75: Viewing angle (degrees)
- Aspect ratio ensures proper scaling
- Clipping planes prevent rendering unnecessary details
3. Renderer Creation
1 const renderer = new THREE.WebGLRenderer();2 renderer.setSize(window.innerWidth, window.innerHeight);3 document.body.appendChild(renderer.domElement);
Translates 3D scene to 2D screen, handling all WebGL complexities automatically.
4. Texture and Sphere Creation
1 const loader = new THREE.TextureLoader();2 loader.load('3d.png', function (texture) {3 const geometry = new THREE.SphereGeometry(200, 20, 20);4 const material = new THREE.MeshBasicMaterial({ map: texture });5 const mesh = new THREE.Mesh(geometry, material);6 group.add(mesh);7 });
Breaks down into:
- Load texture image
- Create sphere geometry
- Apply texture as material
- Combine into a mesh
- Add to scene group
5. Interactive Elements
1 function onDocumentMouseMove(event) {2 mouseX = (event.clientX - 0.5);3 mouseY = (event.clientY - 0.5);4 }
Captures mouse movement to enable dynamic camera positioning.
6. Animation Loop
1 function render() {2 camera.position.x += (mouseX - camera.position.x) * 0.05;3 camera.position.y += (mouseY - camera.position.y) * 0.05;4 group.rotation.y += 0.0005;5 renderer.render(scene, camera);6 }
Continuously updates:
- Camera position based on mouse
- Earth rotation
- Renders each frame
Key Optimization Techniques
- Smooth camera movement using interpolation
- Minimal rotation speeds for natural effect
- Efficient WebGL rendering
Performance Considerations
- Use lower polygon count for faster rendering
- Optimize texture sizes
- Implement lazy loading
Expansion and Improvement Possibilities
- Add cloud layer animation
- Implement country/region highlighting
- Integrate geographic data visualization
Conclusion
Three.js transforms complex 3D rendering into a straightforward, developer-friendly process. By understanding these fundamental concepts, you can create stunning interactive visualizations. Happy coding! 🚀🌍