Okay, here is a single HTML file containing the HTML structure, Bootstrap 5 for styling, and the JavaScript/Three.js code to create an interactive Earth model with rotation, animated water/clouds, and an explode/recreate effect.
Explanation:
- HTML Structure: Sets up a basic page with a container (
#earth-container) for the Three.js canvas and buttons (#explodeBtn, #recreateBtn) for controlling the effect. Bootstrap classes are used for basic styling and layout.
- CSS Styling (
<style> block):
- Basic reset/styling for
body and html.
- Styles the container to take up most of the viewport.
- Styles the buttons using Bootstrap classes (
btn, btn-primary, position-absolute, etc.) and positions them.
- JavaScript (
<script> block):
- Libraries: Includes Three.js and OrbitControls via CDNs.
- Setup: Initializes the scene, camera, renderer, lighting (ambient and directional), and orbit controls.
- Textures: Uses
THREE.TextureLoader to load necessary textures:
earth_texture: The main color map for the Earth.
cloud_texture: For the cloud layer.
water_normal_map: A normal map specifically for the water layer to simulate waves/movement. You'll need to find/download one of these (many are available online, search for "water normal map seamless"). Place the downloaded texture file in the same directory or adjust the path.
- Earth Mesh: Creates a sphere geometry and applies the
earth_texture using MeshStandardMaterial for realistic lighting.
- Cloud Mesh: Creates a slightly larger sphere, applies the
cloud_texture using MeshBasicMaterial (or MeshStandardMaterial), sets it to transparent, and adds an alphaMap (the cloud texture itself often works if it has transparency or a distinct color for transparency) to make the clouds appear puffy and semi-transparent. It scrolls the texture slowly for movement.
- Water Mesh: Creates another slightly larger sphere, uses a
MeshPhongMaterial for a shinier look, sets transparency, and crucially, maps the water_normal_map to the normalMap property. The texture's offset is animated in the animate loop to create the water movement effect.
- Grouping: Places the Earth, Cloud, and Water meshes into a
THREE.Group for easier manipulation (like scaling or moving together during explosion/recreation).
- Animation Loop (
animate):
- Uses
requestAnimationFrame for smooth animation.
- Updates the
OrbitControls.
- Rotates the Earth mesh (
earthMesh.rotation.y += 0.001).
- Rotates the Cloud mesh (
cloudMesh.rotation.y += 0.0005).
- Scrolls the UVs of the
water_normal_map (waterNormalMap.offset.x += 0.0005, waterNormalMap.offset.y += 0.0003) to create the water animation.
- Renders the scene.
- Explode/Recreate Functions:
explodeEarth: Scales the Earth sphere down rapidly while scaling the cloud and water spheres up and slightly outwards, simulating an explosion. Uses flags (isExploded) to prevent multiple explosions.
recreateEarth: Reverses the explosion effect, scaling the Earth back up and the other layers back in. Uses flags to prevent multiple recreations.
- Window Resize: Updates the camera and renderer when the window size changes.
- Event Listeners: Attaches the
explodeEarth and recreateEarth functions to the button clicks.
To Run This:
- Save: Save the entire code block below as an HTML file (e.g.,
earth.html).
- Textures: You MUST download suitable textures and place them in the same folder as the HTML file, or update the paths in the JavaScript code:
- Earth Texture: Search for "earth texture map seamless". A common size is 4096x2048 or 8192x4096. Example filename:
earth_texture.jpg
- Cloud Texture: Search for "earth cloud map seamless". Often a grayscale image. Example filename:
earth_clouds.jpg
- Water Normal Map: Search for "water normal map seamless". This is crucial for the water animation. Example filename:
water_normal.jpg
- Open: Open the
earth.html file in your web browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive Earth</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<style>
body {
margin: 0;
overflow: hidden; /* Prevent scrollbars */
background-color: #000;
font-family: Arial, sans-serif;
}
#info {
position: absolute;
top: 10px;
left: 10px;
color: white;
background-color: rgba(0, 0, 0, 0.5);
padding: 10px;
border-radius: 5px;
z-index: 100; /* Ensure it's above the canvas */
}
#controls {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
z-index: 100;
display: flex;
gap: 15px;
}
canvas {
display: block; /* Remove extra space below canvas */
}
</style>
</head>
<body>
<div id="info">
<p>Three.js Interactive Earth</p>
<p>Drag to rotate, Scroll/Pinch to zoom</p>
</div>
<div id="controls">
<button id="explodeBtn" class="btn btn-warning">Explode!</button>
<button id="recreateBtn" class="btn btn-success">Recreate</button>
</div>
<!-- Three.js Library -->
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.159.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.159.0/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
let scene, camera, renderer, controls;
let earthMesh, cloudMesh, waterMesh, earthGroup;
let waterNormalMap;
let isExploded = false;
let animationTimeout = null;
// --- TEXTURE FILENAMES ---
// IMPORTANT: Replace these with the actual filenames you have downloaded
// and placed in the same directory as this HTML file.
const EARTH_TEXTURE_FILE = 'earth_texture.jpg'; // e.g., from https://visibleearth.nasa.gov/
const CLOUD_TEXTURE_FILE = 'earth_clouds.jpg'; // e.g., from https://www.solarsystemscope.com/textures/
const WATER_NORMAL_MAP_FILE = 'water_normal.jpg'; // e.g., search "water normal map seamless"
function init() {
// 1. Scene
scene = new THREE.Scene();
// 2. Camera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5; // Adjusted initial distance
// 3. Renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement); // Append canvas to body
// 4. Lighting
const ambientLight = new THREE.AmbientLight(0xffffff, 0.3); // Soft white light
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1.5); // Simulates sun
directionalLight.position.set(5, 3, 5);
scene.add(directionalLight);
// 5. Controls
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // Smooths out the control behavior
controls.dampingFactor = 0.05;
controls.screenSpacePanning = false; // Use for panning relative to camera projection
controls.minDistance = 2;
controls.maxDistance = 10;
// 6. Texture Loader
const textureLoader = new THREE.TextureLoader();
// --- Earth ---
const earthGeometry = new THREE.SphereGeometry(2, 64, 64); // Radius 2, high segments
const earthTexture = textureLoader.load(EARTH_TEXTURE_FILE);
// earthTexture.colorSpace = THREE.SRGBColorSpace; // Use if your texture is not sRGB encoded
const earthMaterial = new THREE.MeshStandardMaterial({
map: earthTexture,
// bumpMap: earthTexture, // Optional: Use same texture for bumpiness or load a specific bump map
// bumpScale: 0.05,
// specularMap: earthTexture, // Optional: Use same texture for specular or load specific specular map
// specular: new THREE.Color('grey')
});
earthMesh = new THREE.Mesh(earthGeometry, earthMaterial);
earthMesh.rotation.y = Math.PI / 2; // Initial orientation
// --- Clouds ---
const cloudGeometry = new THREE.SphereGeometry(2.02, 64, 64); // Slightly larger
const cloudTexture = textureLoader.load(CLOUD_TEXTURE_FILE);
// cloudTexture.colorSpace = THREE.SRGBColorSpace; // Use if needed
const cloudMaterial = new THREE.MeshStandardMaterial({ // Or MeshBasicMaterial for no lighting interaction
map: cloudTexture,
transparent: true,
opacity: 0.7,
// alphaMap: cloudTexture, // Use if the texture has transparency info or you want to mask it
// side: THREE.BackSide // Sometimes helps with cloud appearance
});
cloudMesh = new THREE.Mesh(cloudGeometry, cloudMaterial);
// --- Water (Animated Normal Map) ---
const waterGeometry = new THREE.SphereGeometry(2.01, 64, 64); // Slightly larger than Earth
const waterMaterial = new THREE.MeshPhongMaterial({ // Phong reacts better to specular highlights
color: 0x0044ff, // Blueish tint
transparent: true,
opacity: 0.6,
specular: 0xaaaaaa, // Shininess
shininess: 30,
normalScale: new THREE.Vector2(1, 1) // Strength of the normal map
});
// Load the normal map
waterNormalMap = textureLoader.load(WATER_NORMAL_MAP_FILE);
waterNormalMap.wrapS = THREE.RepeatWrapping; // Allow repeating/tiling
waterNormalMap.wrapT = THREE.RepeatWrapping;
waterMaterial.normalMap = waterNormalMap; // Apply the normal map
waterMesh = new THREE.Mesh(waterGeometry, waterMaterial);
// --- Grouping ---
earthGroup = new THREE.Group();
earthGroup.add(earthMesh);
earthGroup.add(cloudMesh);
earthGroup.add(waterMesh);
scene.add(earthGroup);
// Set initial scale for explode/recreate
earthGroup.scale.set(1, 1, 1);
earthMesh.scale.set(1, 1, 1);
cloudMesh.scale.set(1,1,1);
waterMesh.scale.set(1,1,1);
// --- Event Listeners ---
document.getElementById('explodeBtn').addEventListener('click', explodeEarth);
document.getElementById('recreateBtn').addEventListener('click', recreateEarth);
window.addEventListener('resize', onWindowResize);
animate(); // Start the animation loop
}
function explodeEarth() {
if (isExploded) return; // Already exploded
isExploded = true;
console.log("Exploding Earth...");
// Clear any previous timeout
if (animationTimeout) clearTimeout(animationTimeout);
// Smooth explosion effect
const explosionDuration = 1500; // ms
const explosionSteps = 60;
const stepDelay = explosionDuration / explosionSteps;
// Scale down Earth quickly
let currentStep = 0;
animationTimeout = setInterval(() => {
currentStep++;
const progress = currentStep / explosionSteps; // 0 to 1
// Shrink Earth core
earthMesh.scale.setScalar(THREE.MathUtils.lerp(1, 0.1, progress)); // Shrinks to 10% size
// Expand Clouds and Water outwards
const expansionFactor = progress * 0.8; // Max expansion of 0.8 units
cloudMesh.scale.setScalar(THREE.MathUtils.lerp(1, 1.5, progress)); // Scale up clouds
waterMesh.scale.setScalar(THREE.MathUtils.lerp(1, 1.4, progress)); // Scale up water slightly less
// Move clouds and water slightly outwards from center
// Note: Since they are children of earthGroup, scaling achieves some outward movement.
// For more pronounced effect, you could adjust their positions relative to earthGroup,
// but that requires separating them from the group temporarily or managing positions carefully.
if (currentStep >= explosionSteps) {
clearInterval(animationTimeout);
animationTimeout = null;
console.log("Explosion finished.");
}
}, stepDelay);
}
function recreateEarth() {
if (!isExploded) return; // Not exploded yet
isExploded = false;
console.log("Recreating Earth...");
// Clear any previous timeout
if (animationTimeout) clearTimeout(animationTimeout);
// Smooth recreation effect
const recreateDuration = 1500; // ms
const recreateSteps = 60;
const stepDelay = recreateDuration / recreateSteps;
let currentStep = 0;
animationTimeout = setInterval(() => {
currentStep++;
const progress = currentStep / recreateSteps; // 0 to 1
// Restore Earth scale
earthMesh.scale.setScalar(THREE.MathUtils.lerp(0.1, 1, progress)); // Restore from 10%
// Shrink Clouds and Water back inwards
cloudMesh.scale.setScalar(THREE.MathUtils.lerp(1.5, 1, progress));
waterMesh.scale.setScalar(THREE.MathUtils.lerp(1.4, 1, progress));
if (currentStep >= recreateSteps) {
// Ensure final state is exactly 1,1,1
earthMesh.scale.setScalar(1);
cloudMesh.scale.setScalar(1);
waterMesh.scale.setScalar(1);
clearInterval(animationTimeout);
animationTimeout = null;
console.log("Recreation finished.");
}
}, stepDelay);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
// Update controls (for damping)
controls.update();
// Rotate Earth
if (earthGroup) {
earthGroup.rotation.y += 0.0005; // Slower rotation for the group
}
// Rotate Clouds slightly differently
if (cloudMesh) {
// cloudMesh.rotation.y += 0.0002; // Can rotate independently if needed
}
// Animate Water Texture
if (waterNormalMap) {
waterNormalMap.offset.x += 0.0002; // Adjust speed as needed
waterNormalMap.offset.y += 0.0001; // Adjust speed as needed
}
// Render
renderer.render(scene, camera);
}
// --- Initialize ---
// Wait for textures to potentially load or just start
init();
</script>
</body>
</html>
Important Notes:
- Textures: The most critical part is obtaining the texture files (
earth_texture.jpg, earth_clouds.jpg, water_normal.jpg) and placing them correctly or updating the file paths in the code. You can find many textures by searching online (e.g., NASA's Visible Earth, Solar System Scope). The water_normal.jpg is particularly important for the water effect.
- Performance: Higher segment counts (
64, 64 in SphereGeometry) look smoother but require more resources. Adjust if needed.
- File Structure: This code assumes all texture files are in the same directory as the HTML file. If you put them in a subfolder (e.g.,
textures/), you must change the paths like textureLoader.load('textures/earth_texture.jpg').
- Explosion Effect: The current "explosion" scales the Earth down and the other layers up. More complex effects could involve breaking the Earth into many small pieces (using geometries or particle systems), but this provides a basic visual representation.
- Color Space: Modern browsers and Three.js often expect textures to be in sRGB color space. If your Earth texture looks washed out, uncomment the
earthTexture.colorSpace = THREE.SRGBColorSpace; line (and similar lines for other textures if necessary). The default might work fine depending on your browser and texture source.