do a solar system simulation in a single html file
- User
do a solar system simulation in a single html file
Assistant
Okay, here is a complete solar system simulation in a single HTML file using HTML, CSS, and JavaScript with the Canvas API.
It includes the Sun and the 8 main planets, basic orbital motion, adjustable speed, zoom, pan, and optional trails.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Solar System Simulation</title> <style> body { margin: 0; padding: 0; background: #000; /* Black background for space */ overflow: hidden; /* Hide scrollbars */ font-family: Arial, sans-serif; } canvas { display: block; /* Remove extra space below canvas */ cursor: grab; /* Indicate draggable */ } canvas:active { cursor: grabbing; /* Indicate actively dragging */ } .controls { position: absolute; top: 10px; left: 10px; color: white; z-index: 100; /* Ensure controls are above canvas */ background: rgba(0, 0, 0, 0.5); /* Semi-transparent background */ padding: 10px; border-radius: 5px; } .controls button { margin: 5px; padding: 8px 12px; background: rgba(255, 255, 255, 0.2); /* Semi-transparent button */ color: white; border: 1px solid rgba(255, 255, 255, 0.3); border-radius: 4px; cursor: pointer; transition: background 0.3s ease; } .controls button:hover { background: rgba(255, 255, 255, 0.4); } .info { position: absolute; bottom: 10px; left: 10px; color: white; font-size: 12px; opacity: 0.7; z-index: 100; } </style> </head> <body> <canvas id="solarSystemCanvas"></canvas> <div class="controls"> <button onclick="togglePause()">Pause/Play</button> <button onclick="resetView()">Reset View</button> <button onclick="toggleTrails()">Toggle Trails</button> <button onclick="changeSpeed(0.8)">Slower</button> <button onclick="changeSpeed(1.2)">Faster</button> </div> <div class="info"> Drag to pan • Scroll to zoom </div> <script> // --- Canvas Setup --- const canvas = document.getElementById('solarSystemCanvas'); const ctx = canvas.getContext('2d'); // Set canvas size to fill window function resizeCanvas() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; } resizeCanvas(); // Initial resize window.addEventListener('resize', resizeCanvas); // Resize on window change // --- Simulation Variables --- let isPaused = false; let showTrails = true; let simulationSpeed = 1; // Multiplier for orbital speed let zoom = 1; // Zoom level let offsetX = 0; // Pan offset X let offsetY = 0; // Pan offset Y // Drag variables let isDragging = false; let lastMouseX = 0; let lastMouseY = 0; // --- Planet Data --- // Distances and sizes are scaled for visual representation, not actual proportions // Speeds are relative to approximate real orbital periods const planets = [ { name: 'Mercury', distance: 50, // Distance from Sun (scaled) size: 3, // Size (scaled) color: '#A9A9A9',// Grey speed: 0.048, // Orbital speed (scaled angular velocity) angle: Math.random() * Math.PI * 2, // Starting angle (randomized) trail: [] // Array to store trail points }, { name: 'Venus', distance: 80, size: 4.5, color: '#FFD700',// Gold speed: 0.035, angle: Math.random() * Math.PI * 2, trail: [] }, { name: 'Earth', distance: 110, size: 5, color: '#4169E1',// Royal Blue speed: 0.03, angle: Math.random() * Math.PI * 2, trail: [] }, { name: 'Mars', distance: 150, size: 4, color: '#DC143C',// Crimson speed: 0.024, angle: Math.random() * Math.PI * 2, trail: [] }, { name: 'Jupiter', distance: 220, size: 14, color: '#FFA07A',// Light Salmon speed: 0.013, angle: Math.random() * Math.PI * 2, trail: [] }, { name: 'Saturn', distance: 300, size: 12, color: '#DAA520',// Goldenrod speed: 0.0096, angle: Math.random() * Math.PI * 2, trail: [], hasRings: true // Add property for rings }, { name: 'Uranus', distance: 370, size: 8, color: '#40E0D0',// Turquoise speed: 0.0068, angle: Math.random() * Math.PI * 2, trail: [] }, { name: 'Neptune', distance: 430, size: 8, color: '#0000CD',// Medium Blue speed: 0.0054, angle: Math.random() * Math.PI * 2, trail: [] } ]; // --- Control Functions (called by buttons) --- function togglePause() { isPaused = !isPaused; } function resetView() { zoom = 1; offsetX = 0; offsetY = 0; } function toggleTrails() { showTrails = !showTrails; // Clear existing trails if hiding if (!showTrails) { planets.forEach(planet => planet.trail = []); } } function changeSpeed(factor) { simulationSpeed *= factor; // Clamp speed to reasonable range simulationSpeed = Math.max(0.1, Math.min(5, simulationSpeed)); } // --- Mouse and Wheel Event Handlers --- canvas.addEventListener('mousedown', (e) => { isDragging = true; lastMouseX = e.clientX; lastMouseY = e.clientY; canvas.style.cursor = 'grabbing'; }); canvas.addEventListener('mousemove', (e) => { if (isDragging) { // Calculate movement delta const deltaX = e.clientX - lastMouseX; const deltaY = e.clientY - lastMouseY; // Update offsets, scaled inversely by zoom offsetX += deltaX / zoom; offsetY += deltaY / zoom; // Update last mouse position lastMouseX = e.clientX; lastMouseY = e.clientY; } }); canvas.addEventListener('mouseup', () => { isDragging = false; canvas.style.cursor = 'grab'; }); canvas.addEventListener('mouseout', () => { isDragging = false; // Stop dragging if mouse leaves canvas canvas.style.cursor = 'grab'; }); canvas.addEventListener('wheel', (e) => { e.preventDefault(); // Prevent page scroll // Calculate zoom factor based on wheel direction const zoomFactor = e.deltaY > 0 ? 0.9 : 1.1; // Zoom out if deltaY > 0, zoom in otherwise // Get mouse position relative to canvas center (simulation coordinates *before* new zoom) // This point should remain under the cursor after zooming const mouseX = (e.clientX - canvas.width / 2) / zoom - offsetX; const mouseY = (e.clientY - canvas.height / 2) / zoom - offsetY; // Apply zoom zoom *= zoomFactor; // Clamp zoom to a reasonable range zoom = Math.max(0.1, Math.min(3, zoom)); // Allow zoom between 0.1x and 3x // Calculate new offsets to keep the point under the cursor offsetX = -(e.clientX - canvas.width / 2) / zoom + mouseX; offsetY = -(e.clientY - canvas.height / 2) / zoom + mouseY; }); // --- Coordinate Transformation --- // Converts simulation coordinates (relative to Sun at 0,0) to canvas coordinates function transformX(x) { return (x + offsetX) * zoom + canvas.width / 2; } function transformY(y) { return (y + offsetY) * zoom + canvas.height / 2; } // --- Drawing Functions --- function drawStars() { ctx.fillStyle = 'rgba(255, 255, 255, 0.8)'; const numStars = 200; // Simple fixed stars - won't move with pan/zoom, creating a distant background for (let i = 0; i < numStars; i++) { // Use pseudo-randomness for consistent pattern but spread out const x = (Math.sin(i * 1.2345) * 100000) % canvas.width; const y = (Math.cos(i * 6.7890) * 100000) % canvas.height; const size = (Math.sin(i * 9.876) + 1) * 0.5 + 0.5; // Size between 0.5 and 1.5 ctx.beginPath(); // Ensure coordinates are positive and within bounds ctx.arc(Math.abs(x), Math.abs(y), size, 0, Math.PI * 2); ctx.fill(); } } function drawSun() { const sunX = transformX(0); const sunY = transformY(0); const sunRadius = 20 * zoom; // Scaled size // Draw Sun's glow/corona const gradient = ctx.createRadialGradient(sunX, sunY, 0, sunX, sunY, sunRadius * 2); gradient.addColorStop(0, 'rgba(255, 255, 0, 0.8)'); // Inner yellow gradient.addColorStop(0.5, 'rgba(255, 165, 0, 0.4)'); // Middle orange gradient.addColorStop(1, 'rgba(255, 0, 0, 0.1)'); // Outer red ctx.fillStyle = gradient; ctx.beginPath(); ctx.arc(sunX, sunY, sunRadius * 2, 0, Math.PI * 2); ctx.fill(); // Draw Sun's core ctx.fillStyle = '#FFD700'; // Gold ctx.beginPath(); ctx.arc(sunX, sunY, sunRadius, 0, Math.PI * 2); ctx.fill(); } function drawOrbits() { ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)'; // Semi-transparent white ctx.lineWidth = 1; planets.forEach(planet => { ctx.beginPath(); // Draw orbit path as a circle around the Sun's transformed center ctx.arc(transformX(0), transformY(0), planet.distance * zoom, 0, Math.PI * 2); ctx.stroke(); }); } function drawPlanet(planet) { // Calculate planet's position in simulation space const simX = Math.cos(planet.angle) * planet.distance; const simY = Math.sin(planet.angle) * planet.distance; // Transform to canvas coordinates const canvasX = transformX(simX); const canvasY = transformY(simY); const radius = planet.size * zoom; // Scaled size // Draw trail (before planet so planet is on top) if (showTrails && planet.trail.length > 1) { ctx.strokeStyle = planet.color + '60'; // Trail color with some transparency ctx.lineWidth = 1; ctx.beginPath(); // Transform each point in the trail ctx.moveTo(transformX(planet.trail[0].x), transformY(planet.trail[0].y)); for (let i = 1; i < planet.trail.length; i++) { ctx.lineTo(transformX(planet.trail[i].x), transformY(planet.trail[i].y)); } ctx.stroke(); } // Draw Saturn's rings if (planet.hasRings && radius > 5) { // Only draw rings if planet is large enough ctx.strokeStyle = 'rgba(218, 165, 32, 0.6)'; // Goldenrod transparent ctx.lineWidth = 2 * zoom; // Scale line width with zoom ctx.beginPath(); // Draw an ellipse around the planet // Arguments: centerX, centerY, radiusX, radiusY, rotation, startAngle, endAngle ctx.ellipse(canvasX, canvasY, radius * 1.8, radius * 0.5, planet.angle + Math.PI/4, 0, Math.PI * 2); // Simple oblique ring ctx.stroke(); } // Draw planet ctx.fillStyle = planet.color; ctx.beginPath(); ctx.arc(canvasX, canvasY, radius, 0, Math.PI * 2); ctx.fill(); // Optional: Add a subtle highlight ctx.fillStyle = 'rgba(255, 255, 255, 0.3)'; ctx.beginPath(); ctx.arc(canvasX - radius * 0.3, canvasY - radius * 0.3, radius * 0.3, 0, Math.PI * 2); ctx.fill(); } // --- Animation Loop --- function animate() { // Clear canvas ctx.fillStyle = '#000'; ctx.fillRect(0, 0, canvas.width, canvas.height); // Draw background stars drawStars(); // Update planet positions if not paused if (!isPaused) { planets.forEach(planet => { // Update angle based on speed and global simulation speed planet.angle += planet.speed * simulationSpeed * 0.01; // 0.01 factor for finer control // Add current position to trail (in simulation coordinates) const currentSimX = Math.cos(planet.angle) * planet.distance; const currentSimY = Math.sin(planet.angle) * planet.distance; planet.trail.push({ x: currentSimX, y: currentSimY }); // Limit trail length (adjust number based on desired trail length) const maxTrailLength = 200; if (planet.trail.length > maxTrailLength) { planet.trail.shift(); // Remove oldest point } }); } // Draw orbits drawOrbits(); // Draw Sun drawSun(); // Draw planets planets.forEach(planet => { drawPlanet(planet); }); // Request next frame requestAnimationFrame(animate); } // --- Start Simulation --- animate(); </script> </body> </html>How to use:
- Save the entire code block above as an HTML file (e.g.,
solar_system.html). - Open the HTML file in your web browser.
Features:
- Responsive: The canvas resizes with the browser window.
- Planets: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune are simulated.
- Orbits: Circles are drawn to show the approximate orbital paths.
- Sun: A central sun with a simple glow effect.
- Motion: Planets move around the sun at speeds relative to their real-world counterparts (faster closer in, slower further out).
- Interaction:
- Drag the canvas to pan the view.
- Scroll the mouse wheel to zoom in or out.
- Controls: Buttons allow you to:
- Pause/Play the simulation.
- Reset the view (zoom and pan).
- Toggle orbital trails on or off.
- Make the simulation faster or slower.
- Visuals: Basic colors, a subtle highlight on planets, and a simple starfield background. Saturn has simple rings.
Limitations:
- This is a simplified 2D simulation. Orbits are perfect circles (real orbits are ellipses).
- Planet sizes and distances are not to scale simultaneously – distances are compressed to fit on screen, and sizes are exaggerated so you can actually see the planets.
- Gravity is not simulated; planets follow pre-calculated circular paths.
- No moons or other celestial bodies are included.
- Rendering is basic (no complex shading, textures, etc.).
This single file provides a good starting point for a basic interactive solar system visualization in the browser!
- Save the entire code block above as an HTML file (e.g.,
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- gpt-4.1-mini-2025-04-14Compare side by side →
mistral-medium-2505Compare side by side →
command-a-03-2025Compare side by side →
claude-opus-4-20250514Compare side by side →
- grok-3-preview-02-24Compare side by side →
llama-3.3-70b-instructCompare side by side →
claude-opus-4-20250514Compare side by side →
claude-sonnet-4-20250514Compare side by side →
- chatgpt-4o-latest-20250326Compare side by side →
qwen3-235b-a22b-no-thinkingCompare side by side →
deepseek-r1-0528Compare side by side →