Apply gravity between two or more objects in HTML5 Canvas

To apply gravity between two or more objects in HTML5 Canvas, you need to calculate the gravitational force between each pair of objects and update their velocities accordingly.

Gravitational Force Formula

The gravitational force between two objects is calculated using Newton's law of universal gravitation. In our simplified 2D canvas implementation, we use:

F = G * (m1 * m2) / r²

Where F is the force, G is the gravitational constant, m1 and m2 are the masses, and r is the distance between objects.

Basic Gravity Calculation

Here's how to calculate and apply gravity between two objects:

<canvas id="canvas" width="800" height="600"></canvas>

<script>
// Calculate gravity between two objects
function applyGravity(obj1, obj2) {
    var distX = obj1.x - obj2.x;
    var distY = obj1.y - obj2.y;
    
    var distanceSquared = distX * distX + distY * distY;
    var distance = Math.sqrt(distanceSquared);
    
    // Gravitational force (simplified)
    var force = 50 / distanceSquared;
    
    // Unit vector components
    var unitX = distX / distance;
    var unitY = distY / distance;
    
    // Force components
    var forceX = force * unitX;
    var forceY = force * unitY;
    
    // Apply force to velocities (Newton's second law)
    obj1.vx -= forceX;
    obj1.vy -= forceY;
    
    obj2.vx += forceX;
    obj2.vy += forceY;
}

// Test with two objects
var obj1 = { x: 200, y: 300, vx: 0, vy: 0 };
var obj2 = { x: 600, y: 300, vx: 0, vy: 0 };

applyGravity(obj1, obj2);
console.log("Object 1 velocity:", obj1.vx.toFixed(4), obj1.vy.toFixed(4));
console.log("Object 2 velocity:", obj2.vx.toFixed(4), obj2.vy.toFixed(4));
</script>

Complete Gravity Simulation

Here's a complete example with multiple objects and animation:

<canvas id="gravityCanvas" width="800" height="600" style="border: 1px solid #000;"></canvas>

<script>
var canvas = document.getElementById('gravityCanvas');
var ctx = canvas.getContext('2d');

// Object constructor
function GravityObject(x, y, mass, color) {
    this.x = x;
    this.y = y;
    this.vx = 0;
    this.vy = 0;
    this.mass = mass;
    this.radius = Math.sqrt(mass) * 2;
    this.color = color;
}

// Create objects
var objects = [
    new GravityObject(200, 300, 100, 'red'),
    new GravityObject(600, 300, 150, 'blue'),
    new GravityObject(400, 200, 80, 'green')
];

function applyGravityBetweenObjects(obj1, obj2) {
    var distX = obj1.x - obj2.x;
    var distY = obj1.y - obj2.y;
    
    var distanceSquared = distX * distX + distY * distY;
    var distance = Math.sqrt(distanceSquared);
    
    // Prevent division by zero
    if (distance === 0) return;
    
    // Gravitational force with mass consideration
    var force = (obj1.mass * obj2.mass) / distanceSquared * 0.01;
    
    // Unit vector
    var unitX = distX / distance;
    var unitY = distY / distance;
    
    // Force components
    var forceX = force * unitX;
    var forceY = force * unitY;
    
    // Apply force (F = ma, so a = F/m)
    obj1.vx -= forceX / obj1.mass;
    obj1.vy -= forceY / obj1.mass;
    
    obj2.vx += forceX / obj2.mass;
    obj2.vy += forceY / obj2.mass;
}

function updateObjects() {
    // Apply gravity between all pairs
    for (var i = 0; i < objects.length; i++) {
        for (var j = i + 1; j < objects.length; j++) {
            applyGravityBetweenObjects(objects[i], objects[j]);
        }
    }
    
    // Update positions
    for (var i = 0; i < objects.length; i++) {
        objects[i].x += objects[i].vx;
        objects[i].y += objects[i].vy;
    }
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    for (var i = 0; i < objects.length; i++) {
        var obj = objects[i];
        ctx.beginPath();
        ctx.arc(obj.x, obj.y, obj.radius, 0, 2 * Math.PI);
        ctx.fillStyle = obj.color;
        ctx.fill();
    }
}

function animate() {
    updateObjects();
    draw();
    requestAnimationFrame(animate);
}

animate();
</script>

Key Points

  • Distance Calculation: Use Pythagorean theorem to find distance between objects
  • Force Direction: Calculate unit vector to determine force direction
  • Mass Consideration: Heavier objects have stronger gravitational pull
  • Performance: For many objects, consider spatial optimization techniques

Conclusion

Gravity simulation in HTML5 Canvas involves calculating forces between object pairs and updating velocities. The key is proper distance calculation and applying Newton's laws of motion for realistic physics.

Updated on: 2026-03-15T23:18:59+05:30

310 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements