Okay, creating a 3D planet Earth in the browser is most effectively done using a WebGL library like Three.js. Doing it from scratch with pure WebGL is significantly more complex.
This example will use Three.js to create a sphere, map Earth textures onto it, add clouds, light it, and allow you to orbit it with your mouse.
Here's the code structured in a single HTML file for easy demonstration:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3D Earth with Three.js</title>
<style>
body { margin: 0; overflow: hidden; } /* Remove default margins and scrollbars */
canvas { display: block; } /* Make the canvas block element */
#container { width: 100%; height: 100vh; } /* Container for the 3D scene */
</style>
</head>
<body>
<div id="container"></div>
<!-- Include Three.js library from CDN -->
<script src="https://cdn.jsdelivr.net/npm/three@0.164.1/build/three.min.js"></script>
<!-- Include OrbitControls for camera interaction -->
<script src="https://cdn.jsdelivr.net/npm/three@0.164.1/examples/js/controls/OrbitControls.js"></script>
<script>
// --- Setup ---
let scene, camera, renderer, controls;
let earthMesh, cloudsMesh, starfieldMesh;
const container = document.getElementById('container');
function init() {
// Scene: The container for all 3D objects
scene = new THREE.Scene();
scene.background = new THREE.Color(0x000000); // Black background for space
// Camera: Defines what the user sees and from where
camera = new THREE.PerspectiveCamera(
75, // Field of view
window.innerWidth / window.innerHeight, // Aspect ratio
0.1, // Near clipping plane
2000 // Far clipping plane
);
camera.position.z = 5; // Position the camera away from the origin
// Renderer: Handles drawing the scene onto the screen
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement); // Add the renderer's canvas to the HTML
// --- Objects ---
// Texture Loader
const textureLoader = new THREE.TextureLoader();
// Earth Geometry: A sphere
const earthGeometry = new THREE.SphereGeometry(1, 64, 64); // Radius 1, high detail
// Earth Material: Using textures
const earthMaterial = new THREE.MeshStandardMaterial({
map: textureLoader.load('https://cdn.jsdelivr.net/gh/mrdoob/three.js@r164/examples/textures/earth/earth_atmos_2048.jpg'), // Color map
// normalMap: textureLoader.load('https://cdn.jsdelivr.net/gh/mrdoob/three.js@r164/examples/textures/earth/earth_normal_2048.jpg'), // Optional: Normal map for bumps
// specularMap: textureLoader.load('https://cdn.jsdelivr.net/gh/mrdoob/three.js@r164/examples/textures/earth/earth_specular_2048.jpg'), // Optional: Specular map for shininess
// aoMap: textureLoader.load('ao_texture.jpg') // Optional: Ambient occlusion map
});
// Earth Mesh: Combine geometry and material
earthMesh = new THREE.Mesh(earthGeometry, earthMaterial);
scene.add(earthMesh);
// Clouds (Optional but nice): A slightly larger, transparent sphere
const cloudsGeometry = new THREE.SphereGeometry(1.003, 64, 64); // Slightly larger radius
const cloudsMaterial = new THREE.MeshStandardMaterial({
map: textureLoader.load('https://cdn.jsdelivr.net/gh/mrdoob/three.js@r164/examples/textures/earth/earth_clouds_1024.png'), // Cloud texture with transparency
transparent: true,
blending: THREE.AdditiveBlending, // Makes clouds appear brighter
// opacity: 0.8 // Adjust opacity if needed
});
cloudsMesh = new THREE.Mesh(cloudsGeometry, cloudsMaterial);
scene.add(cloudsMesh);
// Starfield Background (Optional): A very large sphere with stars mapped inside
const starfieldGeometry = new THREE.SphereGeometry(1000, 32, 32); // Very large sphere
const starfieldMaterial = new THREE.MeshBasicMaterial({ // Basic material doesn't react to light
map: textureLoader.load('https://cdn.jsdelivr.net/gh/mrdoob/three.js@r164/examples/textures/planets/2k_stars_milky_way.jpg'), // Star texture
side: THREE.BackSide // Render the inside of the sphere
});
starfieldMesh = new THREE.Mesh(starfieldGeometry, starfieldMaterial);
scene.add(starfieldMesh);
// --- Lighting ---
// Ambient light: Provides general illumination so dark side isn't pitch black
const ambientLight = new THREE.AmbientLight(0x333333); // Soft white light
scene.add(ambientLight);
// Directional light: Simulates the sun's light
const sunLight = new THREE.DirectionalLight(0xffffff, 1); // White light, intensity 1
sunLight.position.set(5, 3, 5); // Position the light source
scene.add(sunLight);
// --- Controls ---
// OrbitControls: Allows orbiting, zooming, and panning with mouse/touch
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // Smooth transition when stopping
controls.dampingFactor = 0.05;
controls.screenSpacePanning = false; // Keep camera movement relative to the scene
// --- Event Listeners ---
window.addEventListener('resize', onWindowResize, false);
}
// --- Animation Loop ---
function animate() {
requestAnimationFrame(animate); // Request the next frame
// Auto-rotate Earth and Clouds (optional)
earthMesh.rotation.y += 0.002;
cloudsMesh.rotation.y += 0.0023; // Clouds rotate slightly faster
controls.update(); // Update controls in each frame if enableDamping is true
renderer.render(scene, camera); // Render the scene
}
// --- Handle Window Resizing ---
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight; // Update aspect ratio
camera.updateProjectionMatrix(); // Update camera's projection matrix
renderer.setSize(window.innerWidth, window.innerHeight); // Update renderer size
}
// Initialize and start the animation
init();
animate();
</script>
</body>
</html>
Explanation:
-
HTML Structure:
- Sets up basic HTML5 document.
- Includes a
<style> block to remove default margins and make the canvas fill the viewport.
- A
div with id="container" will hold the 3D scene rendered by Three.js.
- Includes the Three.js library (
three.min.js) and the OrbitControls script from a CDN. These need to be loaded before our main script.
-
CSS:
- Removes default
margin and hides overflow on the body to ensure the 3D scene fills the screen without scrollbars.
- Sets
display: block on the canvas to prevent extra space below it.
- Sets the container
div to 100% width and 100vh height.
-
JavaScript (Three.js):
init() function:
scene: Created to hold everything.
camera: Set up as a PerspectiveCamera, mimicking human vision. Its position is set back to view the Earth.
renderer: WebGLRenderer is created to draw the scene using the GPU. It's sized to the window and its canvas element is added to the container div.
textureLoader: An instance of THREE.TextureLoader is created to load image files asynchronously.
- Earth:
SphereGeometry: Defines the shape (a sphere). Parameters are radius, width segments, and height segments (higher numbers mean smoother sphere but more polygons).
MeshStandardMaterial: A material that reacts to light, suitable for realistic surfaces. map is set to the URL of an Earth texture (an equirectangular projection). Optional normalMap and specularMap can be added for more detail if you have those textures.
Mesh: Combines the geometry and material. The earthMesh is added to the scene.
- Clouds:
- Another
SphereGeometry is created, slightly larger than the Earth sphere.
- A
MeshStandardMaterial is used with a cloud texture. is crucial for the clouds to show through. can give a nice hazy effect.
To use this code:
- Save the code as an
.html file (e.g., earth.html).
- Open the file in a web browser.
You should see a rotating 3D Earth with clouds and a starry background, which you can click and drag to rotate, scroll to zoom, and right-click+drag to pan.