Leapfrog

The beauty of the leapfrog algorithm: http://en.wikipedia.org/wiki/Leapfrog_integration Image by Alex Proimos: http://www.flickr.com/photos/proimos/7810727314 Click the screen to reset

by Javier Graciá Carpio

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

JavaScript

var sketch = function (p) {
    // Global variables
    var img;
    var solarSystems = [];
    var stepsPerFrame = 10;
    var timeStep = 0.02;

    // Load the image before the sketch is run
    p.preload = function () {
        // Image by Alex Proimos: http://www.flickr.com/photos/proimos/7810727314
        img = p.loadImage("http://farm9.staticflickr.com/8424/7810727314_b6149fb472_c.jpg");
    };

    // Initial setup
    p.setup = function () {
        // Create the canvas
        var canvas = p.createCanvas(img.width, img.height);

        // Start a new drawing each time the mouse is pressed inside the canvas
        canvas.mousePressed(startNewDrawing);

        // Initialize the solar systems
        solarSystems = createSolarSystems(10);

        // Load the image pixels to be able to read them
        img.loadPixels();
    };

    // Execute the sketch
    p.draw = function () {
        // Do several steps per frame
        var step, i;

        for (step = 0; step < stepsPerFrame; step++) {
            for (i = 0; i < solarSystems.length; i++) {
                // Paint all the solar system
                solarSystems[i].paintPlanetsWithImg(img, 0.5);

                // Update the planets positions
                solarSystems[i].update(timeStep);
            }
        }
    };

    //
    // Creates a new set of solar systems
    //
    createSolarSystems = function (nSolarSystems) {
        var i, starPos, starMass, nPlanets;
        var newSolarSystems = [];

        for (i = 0; i < nSolarSystems; i++) {
            starPos = p.createVector(p.random(0.3, 0.7) * p.width, p.random(0.3, 0.7) * p.height);
            starMass = p.random(0.5, 2) * 3000000;
            nPlanets = Math.round(p.random(5, 10));
            newSolarSystems[i] = new SolarSystem(starPos, starMass, nPlanets);
        }

        return newSolarSystems;
    };

    //
    // Starts a new drawing
    //
    startNewDrawing = function () {
        // Clean the screen
       ...