JavaScript Development Space

Create Immersive 3D Earth with Three.js: Interactive WebGL

Add to your RSS feed23 January 20254 min read
Create Immersive 3D Earth with Three.js: Interactive WebGL

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

  • Three.js: 3D rendering library
  • Vite: Modern frontend build tool
  • JavaScript (ES6+)

Required Resources

High-resolution earth texture

Earth map

1. Project Initialization

Quick project setup with Vite:

bash
1 npm create vite@latest earth-3d -- --template vanilla
2 cd earth-3d
3 npm install three

Change the index.html file to include the main js file:

html
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8" />
5 <link
6 rel="icon"
7 type="image/svg+xml"
8 href="/vite.svg" />
9 <meta
10 name="viewport"
11 content="width=device-width, initial-scale=1.0" />
12 <title>3D Earth</title>
13 </head>
14 <body>
15 <script
16 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:

js
1 import './style.css';
2 import * as THREE from 'three';
3
4 // Create the 3D scene
5 const scene = new THREE.Scene();
6
7 // Get canvas element (optional in this example)
8 const canvas = document.getElementById('webglcanvas');
9
10 // Create perspective camera
11 const camera = new THREE.PerspectiveCamera(
12 75, // Field of View (FOV)
13 window.innerWidth / window.innerHeight, // Aspect Ratio
14 0.1, // Near clipping plane
15 1000 // Far clipping plane
16 );
17 camera.position.z = 500; // Position camera away from the scene
18
19 // Create WebGL renderer
20 const renderer = new THREE.WebGLRenderer();
21 renderer.setSize(window.innerWidth, window.innerHeight);
22 document.body.appendChild(renderer.domElement);
23
24 // Create a group to manage 3D objects
25 const group = new THREE.Group();
26 scene.add(group);
27
28 // Mouse position tracking variables
29 let mouseX = 0, mouseY = 0;
30
31 // Texture loader for earth image
32 const loader = new THREE.TextureLoader();
33 loader.load('3d.png', function (texture) {
34 // Create sphere geometry
35 const geometry = new THREE.SphereGeometry(200, 20, 20);
36
37 // Create material with loaded texture
38 const material = new THREE.MeshBasicMaterial({
39 map: texture
40 });
41
42 // Create mesh by combining geometry and material
43 const mesh = new THREE.Mesh(geometry, material);
44 group.add(mesh);
45
46 // Add mouse move event listener
47 document.addEventListener('mousemove', onDocumentMouseMove, false);
48 });
49
50 // Mouse move handler
51 function onDocumentMouseMove(event) {
52 // Normalize mouse coordinates
53 mouseX = (event.clientX - 0.5);
54 mouseY = (event.clientY - 0.5);
55 }
56
57 // Window resize handler
58 function onWindowResize() {
59 // Update camera aspect ratio
60 camera.aspect = window.innerWidth / window.innerHeight;
61 camera.updateProjectionMatrix();
62
63 // Resize renderer
64 renderer.setSize(window.innerWidth, window.innerHeight);
65 }
66
67 // Render and animation function
68 function render() {
69 // Smoothly move camera based on mouse position
70 camera.position.x += (mouseX - camera.position.x) * 0.05;
71 camera.position.y += (mouseY - camera.position.y) * 0.05;
72
73 // Ensure camera looks at the scene center
74 camera.lookAt(scene.position);
75
76 // Rotate earth slowly
77 group.rotation.y += 0.0005;
78 group.rotation.x += 0.00001;
79
80 // Render the scene
81 renderer.render(scene, camera);
82 }
83
84 // Animation loop
85 function animate() {
86 requestAnimationFrame(animate);
87 render();
88 }
89
90 // Start the animation
91 renderer.setAnimationLoop(animate);

Understanding the Code: A Line-by-Line Breakdown

1. Scene Setup

js
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

js
1 const camera = new THREE.PerspectiveCamera(
2 75, // Field of View (FOV)
3 window.innerWidth / window.innerHeight, // Aspect Ratio
4 0.1, // Near clipping plane
5 1000 // Far clipping plane
6 );

The camera mimics human vision:

  • 75: Viewing angle (degrees)
  • Aspect ratio ensures proper scaling
  • Clipping planes prevent rendering unnecessary details

3. Renderer Creation

js
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

js
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

js
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

js
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! 🚀🌍

JavaScript Development Space

© 2025 JavaScript Development Space - Master JS and NodeJS. All rights reserved.