📜 ⬆️ ⬇️

Create a galaxy in 30 lines.

X * is there a game, I thought, and let's scribble in the recovery mode. We will write on jQuery, yes, the meaning of 30 lines is leveled, but I'm awesome so I put on a general extravaganza and cut free karma (no matter how, the reader thought and snapping the mice minus, and I continued thinking) .

People didn't really like my intro, so I paraphrase: "Let's start."

The article is designed for beginners, so respected experts can immediately scroll.
')
image



Instructions for making



We need a function that would perform a looping animation on given parameters, like this one.

function mooveItem(item, speed, pos, direction) { /*          , ..            */ if(isNaN(item.ldir)) item.ldir = pos.min; if(isNaN(item.tdir)) item.tdir = pos.min; /*    ..       ,    */ if(direction == "h") item.ldir = item.ldir == pos.max ? pos.min : pos.max; if(direction == "v") item.tdir = item.tdir == pos.max ? pos.min : pos.max; /*        */ var animation = direction == "v" ? { top : item.tdir } : { left : item.ldir }; /*      */ item.animate(animation, { duration : speed, complete : function() { mooveItem(item, speed, pos, direction); }, queue : false //     ,        }); } 


Now we would have a function that would create an object and assign an animation to it.

 function addPlanet() { var bodyw = $("body").innerWidth(); var bodyh = $(window).height(); /*      () ,        (   ) */ var size = Math.floor(Math.random() * 50); var speed = size * 1000; var obj = $("<div>"); obj .addClass("obj") .css("left", bodyw / 2) .css("top", bodyh / 2) .css("width", size) .css("height", size); /*   */ /*      ,   10         */ mooveItem(obj, speed, { min: size * 10, max: bodyw - size * 10 }, "h"); /*      2/4  3/4  */ mooveItem(obj, speed, { min: bodyh / 2 - 100, max: bodyh / 2 + 100 }, "v"); $("body").append(obj); } 


Create a couple of CSS rules for the appearance of the object.
By the way, if anyone knows why the animation with position: absolute; happens faster than with position: fixed ;, I will be glad to find out.

 body { background: #000; } .obj { border-radius: 50%; opacity: 1; box-shadow: 0px 0px 15px #fff; border-radius: 50%; position: absolute; background: #fff; } 


Well, now all this should be run

 $(window).load(function() { /*    100,    */ for(i=1; i<100; i++) addPlanet(); }); 


Look at the beauty of JS Fiddle, look better on the whole screen.

Example 1, on the topic
Example 2, reminds a big bang

What are the nuances? Periodically, the fire bug diagnoses Too much recursion , depends on the number, size and speed of objects, so sometimes the script does not work out to the end and you see fewer objects than it should be, just restart. And again, if anyone knows where and how to throw an exception correctly, I will be glad to help, because I myself can not figure out.

Source: https://habr.com/ru/post/202858/


All Articles