Skip to content

Instantly share code, notes, and snippets.

@cherdarchuk
Forked from syntagmatic/index.html
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cherdarchuk/73106a65d0c66b2660dd to your computer and use it in GitHub Desktop.
Save cherdarchuk/73106a65d0c66b2660dd to your computer and use it in GitHub Desktop.
Little Black Hole
<!DOCTYPE html>
<meta charset="utf-8">
<canvas id="canvas"></canvas>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var num = 10000;
var canvas = document.getElementById("canvas");
var width = canvas.width = 960;
var height = canvas.height = 500;
var ctx = canvas.getContext("2d");
var CoG = null;
var rad = 20;
var particles = d3.range(num).map(function(i) {
return [Math.round(width*Math.random()), Math.round(height*Math.random())];
});
d3.select("canvas").on("mouseout",CofGravityGone).on("mousemove",CofGravity)
d3.timer(step);
d3.timer(function(){ctx.fillStile})
function CofGravityGone(e){
CoG = null;
}
function CofGravity(e){
CoG = d3.mouse(this);
}
function sign(x) { return x > 1 ? 1 : x < -1 ? -1 : 0; }
function moveit(p) {
var rand = Math.random();
var dx=p[0] - CoG[0];
var dy=p[1] - CoG[1];
var dist = Math.sqrt(dx*dx+dy*dy);
if (dist > rad || Math.random() < 0.7){
if (rand*2 < Math.abs(dx)/(Math.abs(dx)+Math.abs(dy))){p[0] += sign(CoG[0]-p[0]);}
else if (rand >0.5 && rand <=0.75) {p[0] += Math.round(2*Math.random()-1);}
else if (rand >0.75){p[1] += Math.round(2*Math.random()-1);}
else{p[1] += sign(CoG[1]-p[1]);}
}
else {
if (rand*2 < Math.abs(dx)/(Math.abs(dx)+Math.abs(dy))){p[0] += -sign(CoG[0]-p[0])*rad+Math.random()*rad;}
else if (rand >0.5) {
p[0] = Math.round(width*Math.random());
p[1] = Math.round(height*Math.random());
}
else{p[1] += -sign(CoG[1]-p[1])*rad+Math.random()*rad;}
}
return p;
}
function step() {
ctx.fillStyle = "rgba(0,0,0,0.2)";
ctx.fillRect(0,0,width,height);
ctx.fillStyle = "rgba(193,107,240,1)";
particles.forEach(function(p, i) {
if (i == Math.round(num/4)) ctx.fillStyle = "rgba(71,100,226,1)";
if (i == Math.round(num/2)) ctx.fillStyle = "rgba(255,255,255,1)";
if (i == Math.round((num/4)*3)) ctx.fillStyle = "rgba(142,43,46,1)";
if (CoG != null) {
p = moveit(p);
}
else {
p[0] += Math.round(2*Math.random()-1);
p[1] += Math.round(2*Math.random()-1);
}
if (p[0] < 0) p[0] = width;
if (p[0] > width) p[0] = 0;
if (p[1] < 0) p[1] = height;
if (p[1] > height) p[1] = 0;
drawPoint(p);
});
};
function drawPoint(p) {
ctx.fillRect(p[0],p[1],1,1);
};
</script>
<style>
html, body { margin: 0; padding: 0; }
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment