write a simple solar system simulator using newtons laws that uses javascript, html and a canvas all on one page so that I can open the single html page with my browser and run the simulation.
Assistant
Here's a simple solar system simulator using Newton's laws of motion, implemented in JavaScript, HTML, and a canvas element all on a single page. Save the following code into an HTML file (e.g., solar_system_simulator.html) and open it in your browser to run the simulation.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Solar System Simulator</title>
<style>
canvas {
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="canvas" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const G = 6.67430e-11; // gravitational constant
const timeStep = 1; // time step in seconds
// Solar system bodies
const bodies = [
{ mass: 1.989e30, position: { x: 0, y: 0 }, velocity: { x: 0, y: 0 } }, // Sun
{ mass: 5.972e24, position: { x: 147e9, y: 0 }, velocity: { x: 29.78e3, y: 0 } }, // Earth
];
function drawBody(body) {
ctx.beginPath();
ctx.arc(body.position.x, body.position.y, 5 * Math.sqrt(body.mass), 0, 2 * Math.PI);
ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
ctx.fill();
}
function calculateForces() {
for (let i = 0; i < bodies.length; i++) {
const body1 = bodies[i];
for (let j = i + 1; j < bodies.length; j++) {
const body2 = bodies[j];
const dx = body2.position.x - body1.position.x;
const dy = body2.position.y - body1.position.y;
const distance = Math.sqrt(dx * dx + dy * dy);
const forceMagnitude = G * body1.mass * body2.mass / (distance * distance);
const forceDirection = { x: dx / distance, y: dy / distance };
const force = { x: forceMagnitude * forceDirection.x, y: forceMagnitude * forceDirection.y };
body1.velocity.x += force.x / body1.mass * timeStep;
body1.velocity.y += force.y / body1.mass * timeStep;
body2.velocity.x -= force.x / body2.mass * timeStep;
body2.velocity.y -= force.y / body2.mass * timeStep;
}
}
}
function updatePositions() {
for (const body of bodies) {
body.position.x += body.velocity.x * timeStep;
body.position.y += body.velocity.y * timeStep;
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (const body of bodies) {
drawBody(body);
}
requestAnimationFrame(draw);
}
setInterval(() => {
calculateForces();
updatePositions();
}, 1000 / 60); // Update forces and positions 60 times per second
draw();
</script>
</body>
</html>
This code defines a simple solar system with the Sun and Earth, calculates gravitational forces between them using Newton's law of universal gravitation, and updates their positions and velocities accordingly. The draw function continuously updates the canvas to display the positions of the bodies.