Skip to content

Instantly share code, notes, and snippets.

@armollica
Last active January 6, 2018 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save armollica/07123dbc0815fb43decb to your computer and use it in GitHub Desktop.
Save armollica/07123dbc0815fb43decb to your computer and use it in GitHub Desktop.
Floating Particles
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
body {
background-color: black;
}
</style>
</head>
<body>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var width = 960,
height = 500;
var scale = {
x: d3.scale.linear().domain([0, 1]).range([0, width]),
y: d3.scale.linear().domain([0, 1]).range([height, 0]),
r: d3.scale.linear().domain([0, 1]).range([1, 4]),
a: d3.scale.linear().domain([0, 1]).range([.1, .6])
};
var canvas = d3.select("body").append("canvas")
.attr("width", width)
.attr("height", height);
var context = canvas.node().getContext("2d");
var particles = d3.range(1000)
.map(function() {
return {
x: Math.random(),
y: Math.random(),
r: Math.random(),
t: Math.random()*2*Math.PI
};
});
draw(particles);
setInterval(function() {
particles = tick(particles);
draw(particles);
}, 66);
function tick(particles) {
return particles.map(function(d) {
d.t += Math.random()*.5 - .25;
d.x += .001*Math.cos(d.t);
d.y += .001*Math.sin(d.t);
d.r += Math.random()*.01 - .005;
if (d.x < 0 || d.x > width) {
d.x = .5;
d.r = .1;
}
if (d.y < 0 || d.y > height) {
d.y = .5;
d.r = .1;
}
if (d.r <= 0) d.r = .1;
return d;
});
}
function draw(particles) {
context.clearRect(0, 0, width, height);
particles.forEach(function(d) {
var x = scale.x(d.x),
y = scale.y(d.y),
r = scale.r(d.r),
a = scale.a(d.r);
context.beginPath()
context.arc(x, y, r, 0, 2*Math.PI);
context.fillStyle = "rgba(255, 255, 255," + a + ")";
context.fill();
});
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment