Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <span class="tip">Click and drag to create new planet. <br> Click on planet for delete.</span>

<div id="container"></div>

<a class="copyright" href="http://s7at1c.ru">sysoev &copy;</a>

<!-- OBJECTS -->
<script src="js/layer.js"></script>
<script src="js/gbody.js"></script>

<!-- APP -->
<script src="js/app.js"></script>
              
            
!

CSS

              
                body {
            background: #222b34;
        }
        canvas {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }
        .tip {
            position: fixed;
            top: 18px;
            right: 18px;
            z-index: 100;
            color: #7b8481;
        }
        .copyright {
            position: fixed;
            bottom: 18px;
            right: 18px;
            z-index: 102;
            color: #5796bf;
            font-family: Helvetica, sans-serif;
        }
              
            
!

JS

              
                var APP = {};

APP.layers = (function () {
    var layers = {};

    return {
        /**
         * Add new layer in layers stack
         * @param  {string} cont selector for layer container
         * @param  {string} name of new layer
         * @param  {number} zindex
         * @return {APP.layers}
         */
        add_layer: function (cont, layer_name, zindex) {
            zindex = zindex || 0;
            if (typeof layers[layer_name] === "undefined") {
                var tpl = '<canvas id="'+layer_name+'" style="z-index: '+zindex+'"></canvas>';

                cont = $(cont);
                cont.append(tpl);

                var canvas = document.getElementById(layer_name);
                    canvas.width = cont.width();
                    canvas.height = $(window).height();
                var ctx = canvas.getContext("2d");

                layers[layer_name] = {
                    params: {
                        zindex: zindex,
                        ctx: ctx,
                        width: canvas.width,
                        height: canvas.height
                    },
                    objects: []
                };
            } else {
                throw "Layer with name '" + layer_name + "'' alredy exists!";
            }
            return this;
        },

        /**
         * Add object to layer
         * @param  {string} layer_name name of layer where add the object
         * @param  {object} obj        GBody object
         * @return {APP.layers}
         */
        add_obj: function (layer_name, obj) {
            if (layers[layer_name]) {
                layers[layer_name].objects.push(obj);
            } else {
                throw "Layer with name '" + layer_name + "'' does not exists!";
            }
            return this;
        },

        delete_obj: function (layer_name, name) {
            if (layers[layer_name]) {

                for (var i = 0, max = layers[layer_name].objects.length; i < max; i++) {
                    if (layers[layer_name].objects[i].name === name) {
                        layers[layer_name].objects.splice(i,1);
                        break;
                    }
                }
            } else {
                throw "Layer with name '" + layer_name + "'' does not exists!";
            }
            return this;
        },

        click: function (layer_name, coords, fn) {
            fn(layers[layer_name].objects, coords);
        },

        /**
         * Draw all objects in layer
         * @param  {string} layer_name
         * @param  {array} objects
         * @return {APP.layers}
         */
        draw: function (layer_name, objects) {
            if (layers[layer_name]) {

                layers[layer_name].params.ctx.clearRect(0, 0,
                    layers[layer_name].params.width,
                    layers[layer_name].params.height);

                for (var i = 0, max = layers[layer_name].objects.length; i < max; i++) {
                    if (layers[layer_name].objects[i]) {
                        layers[layer_name].objects[i].update(objects);
                        layers[layer_name].objects[i].draw(layers[layer_name].params.ctx, layers[layer_name].params.name);
                    }
                }
            } else {
                throw "Layer with name '" + layer_name + "'' does not exists!";
            }
            return this;
        }
    };
})();

APP.GBody = function (name, pos, color, size, mass, time, active) {
    if (!(this instanceof APP.GBody)) {
        return new APP.GBody(pos, color, size, mass, time, active);
    }

    this.degree = function (degrees) {
        return degrees * (Math.PI / 180);
    };
    this.normalizeAngle = function (radians) {
        var deg360 = Math.PI * 2;
        radians %= deg360;

        return radians + ( radians < 0 ? deg360 : 0 );
    };

    var colors = [
        "#67ced3", '#0bbc9f', '#ffab89',
        '#21af65', '#2f99e3', '#9b58b5',
        "#1bbc9b", '#a5f0ed', '#b3454e',
        '#7aba40'
    ];
    this.name = name;
    this.pos   = pos || {x:0, y:0};
    this.color = color || colors[Math.floor(Math.random() * colors.length)];
    this.size  = size || 20;
    this.mass  = mass || 20;
    this.active = active || false;

    this.speed = this.degree(360) / 1000 / time;
    this.angle = 0;
    this.time = 1;
    this.radius = 0;

    this.distance = function (point) {
        var catet1 = this.pos.x - point.x,
            catet2 = this.pos.y - point.y;
        return Math.sqrt(catet1*catet1 + catet2*catet2);
    };

    this.diff = function (point) {
        var x = this.pos.x - point.x,
            y = this.pos.y - point.y;
        return {x:x, y:y};
    };

    this.g_force = function (dist, mass) {
        return ((this.mass * mass) / dist*dist) / 11000000;
    };

    this.centr_force = function (dist) {
        var speed2 = Math.pow(this.speed*10000, 2) / 10;
        return -(this.mass * (speed2 / dist));
    };

    this.apply_force = function (force, center) {
        if (center.x > this.pos.x) {
            this.pos.x += force;
        } else {
            this.pos.x -= force;
        }
        if (center.y > this.pos.y) {
            this.pos.y += force;
        } else {
            this.pos.y -= force;
        }
    };

    /**
     * Update object
     * @return {undefined}
     */
    this.update = function (objects) {
        if (this.active) {
            var solar_center = {x:$(window).width()/2, y:$(window).height()/2},
                angle = this.time * this.speed,
                radius = this.distance(solar_center),
                sides = this.diff(solar_center),
                c_force = this.centr_force(radius);

            this.radius = Math.floor(radius);

            var newAngle = Math.atan2(sides.x, sides.y) - angle * 50;

            var x = Math.sin(newAngle) * radius + solar_center.x;
            var y = Math.cos(newAngle) * radius + solar_center.y;

            this.pos.x = x;
            this.pos.y = y;

            for (var i = 0, max = objects.length; i < max; i++) {
                if (this.name !== objects[i].name) {
                    var gf = this.g_force(radius, objects[i].mass);
                    this.apply_force(gf, objects[i].pos);
                }
            }

            this.apply_force(c_force, solar_center);
        }
    };

    /**
     * Draw object
     * @param  {object} ctx canvas context
     * @return {undefined}
     */
    this.draw = function (ctx) {

        if (this.name !== "sun") {
            ctx.save();

            ctx.fillStyle = "#fff";
            ctx.textAlign = "center";
            ctx.fillText(this.radius, this.pos.x, this.pos.y + this.size + 5);

            ctx.restore();

            ctx.save();
            ctx.globalAlpha = 0.15;
            ctx.strokeStyle = this.color;
            ctx.beginPath();
            ctx.moveTo(this.pos.x, this.pos.y);
            ctx.lineTo($(window).width()/2, $(window).height()/2);
            ctx.closePath();
            ctx.stroke();

            ctx.beginPath();
            ctx.arc($(window).width()/2, $(window).height()/2, this.radius, 0, Math.PI*2, false);
            ctx.closePath();
            ctx.stroke();
            ctx.globalAlpha = 0.02;
            ctx.fillStyle = this.color;
            ctx.fill();

            ctx.restore();
        }

        ctx.save();

        ctx.beginPath();
        ctx.arc(this.pos.x, this.pos.y, this.size/2, 0, Math.PI*2, false);
        ctx.closePath();
        ctx.fillStyle = this.color;
        ctx.fill();
        ctx.strokeStyle = this.color;
        ctx.lineWidth = this.size / 2.5;
        ctx.globalAlpha = 0.3;
        ctx.stroke();

        ctx.restore();
    };
};

var distance;
distance = function (p1, p2) {
    var catet1 = p1.x - p2.x,
        catet2 = p1.y - p2.y;
    return Math.sqrt(catet1*catet1 + catet2*catet2);
};

/**
 * Main DEMO controller
 * @return {undefined}
 */
APP.controller = function () {
    var i,
        layers = APP.layers,
        requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
                                window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;

    window.requestAnimationFrame = requestAnimationFrame;

    var center = {x: $(document).width()/2, y:$(document).height()/2},
        count = 0;

    var gen_rnd_planet;
    gen_rnd_planet = function(x, y, id) {
        var size = Math.floor(Math.random()*40) + 10;
        var mass = Math.floor(Math.random()*40) + 10;
        var time = Math.floor(Math.random()*120) + 50;
        return new APP.GBody("planet"+id, {x: x, y:y}, false, size, mass, time, true);
    };

    layers.add_layer("#container", "sun", 2);
    layers.add_layer("#container", "planets", 1);
    layers.add_layer("#container", "tmp", 3);

    var objects = [
        new APP.GBody("sun", center, '#fbc118', 110, 100, 0)
    ];

    var x = $(document).width()/2 + 50,
        y = $(document).height()/2 + 50;
    for (i = 0; i < 3; i++) {
        x += Math.floor(Math.random()*50) + 40;
        y += Math.floor(Math.random()*50) + 40;
        count += 1;
        objects.push(gen_rnd_planet(x, y, i));
    }

    for (i = 0, max = objects.length; i < max; i++) {
        if (i === 0) {
            layers.add_obj("sun", objects[i]);
            layers.draw("sun");
        } else {
            layers.add_obj("planets", objects[i]);
        }
    }

    /**
     * Game draw logic
     */
    var step;
    step = function() {
        layers.draw("planets", objects);
        layers.draw("tmp", []);

        requestAnimationFrame(step);
    };

    /**
     * Drag on canvas on canvas
     */
    var drag = 0,
        drag_start_pos = {x:0,y:0},
        drag_cont = $("#container"),
        tmp_planet = false;

    drag_cont.mousedown(function (evt) {
        drag = 1;
        drag_start_pos.x = evt.pageX;
        drag_start_pos.y = evt.pageY;
    }).mousemove(function (evt) {
        var cur_pos = {x: evt.pageX, y:evt.pageY};
        var size = distance(drag_start_pos, cur_pos);

        if (size < 10) {
            size = 10;
        } else if (size > 80) {
            size = 80;
        }

        if (drag === 1) {
            var mass = Math.floor(Math.random()*40) + 10;
            var time = Math.floor(Math.random()*120) + 50;
            tmp_planet = new APP.GBody("tmp_planet", drag_start_pos, false, size, mass, time, 0);
            layers.add_obj("tmp", tmp_planet);

            drag = 2;
        } else if (tmp_planet) {
            tmp_planet.size = size;
        }
    }).mouseup(function (evt) {

        if (drag === 2) {
            drag = 0;
            objects.push(new APP.GBody("planet"+objects.length,
                tmp_planet.pos,
                tmp_planet.color,
                tmp_planet.size,
                tmp_planet.mass,
                0,
                true));

            objects[objects.length-1].speed = tmp_planet.speed;

            layers.add_obj("planets", objects[objects.length-1]);

            tmp_planet = null;
            drag_start_pos = {x:0,y:0};
        } else {
            drag = 0;
            layers.click('planets', {x: evt.pageX, y: evt.pageY}, function (objs, coords) {
                for (var i = 0, max = objs.length; i < max; i++) {
                    var r = objs[i].size/2,
                        s = objs[i].size / 2.5;
                    if ((coords.x > objs[i].pos.x - r - s) && (coords.x < objs[i].pos.x + r + s) &&
                        (coords.y > objs[i].pos.y - r - s) && (coords.y < objs[i].pos.y + r + s)) {
                        layers.delete_obj('planets', objs[i].name);
                        break;
                    }
                }
            });
        }

        layers.delete_obj("tmp", "tmp_planet");
    });

    requestAnimationFrame(step);
};

$(function(){
    APP.controller();
});
              
            
!
999px

Console