Skip to content

Instantly share code, notes, and snippets.

@ikonikre
Created September 30, 2016 05:05
Show Gist options
  • Select an option

  • Save ikonikre/dbeff5271cdf104ffdf91b446494df83 to your computer and use it in GitHub Desktop.

Select an option

Save ikonikre/dbeff5271cdf104ffdf91b446494df83 to your computer and use it in GitHub Desktop.
Milky Way

Milky Way

This programmatically generates a star field. The stars group around a curve which creates a look like the Milky Way. The stars also twinkle slightly.

A Pen by Viper Bailey on CodePen.

License.

_.defer(function() {
var width = $(window).width();
var height = $(window).height();
function pt_random() {
return {
x: Math.random()*width,
y: Math.random()*height
};
};
function circle(i) {
var cx = width/2;
var cy = height/2;
var rad = width/6;
return { x:cx+rad*Math.cos(i*2*Math.PI), y:cy+rad*Math.sin(i*2*Math.PI) };
}
function line(i) {
return { x:width*i, y:height-((height/4)+(.5*height)*i) };
}
function pt_multi() {
var generators = arguments;
var total = 0;
for ( var i=0; i<arguments.length; i+=2 ) {
total += arguments[i];
}
return function() {
var r = Math.random()*total;
for ( var i=0; i<generators.length; i+=2 ) {
r -= generators[i];
if ( r <= 0 ) {
var pt = generators[i+1]();
return pt;
}
}
};
}
function pt_curve(curve,spread) {
spread = spread || 5000;
return function() {
var rnd = Math.random();
var pt = curve(rnd);
var pt2 = curve(rnd+.001);
var slope = {y:pt2.x-pt.x,x:pt.y-pt2.y};
var h2 = height/2;
var mult = h2/Math.log(1+spread);
var y = h2-Math.log(Math.random()*spread+1)*mult;
if ( Math.random() > .5 )
y = -y
pt.x += y*slope.x;
pt.y += y*slope.y;
return pt;
}
}
var point_generator = pt_multi(1,pt_random,7,pt_curve(line));
for ( var i=0; i<5; i++ ) {
var canvas = $("<canvas width='"+width+"' height='"+height+"'>").appendTo($("body"));
var ctx = canvas[0].getContext("2d");
ctx.fillStyle = "white";
canvas.css({WebkitAnimation: "bob " + ((Math.random()*5+2.5)+"s") + " infinite" });
for ( var j=0; j<200; j++ ) {
var pt = point_generator();
var x = pt.x;
var y = pt.y;
var r = Math.random()*1.7 + .5;
ctx.beginPath();
ctx.arc(x,y,r,0,Math.PI*2,true);
ctx.fill();
}
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js"></script>
body {
background-color: black;
}
canvas {
position: absolute;
left: 0px;
top: 0px;
-webkit-filter: blur(1px);
}
@-webkit-keyframes bob {
0% { opacity: 1 }
50% { opacity: .5 }
100% { opacity: 1 }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment