A modification of Mike Bostock's Connected Particles. An exercise to become familiar with the canvas. Varied the circle size to give some element of depth, and turned the lines into curves.
-
-
Save Brideau/561a24c87af72d745aec to your computer and use it in GitHub Desktop.
Connected Particles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<html> | |
<head> | |
<title></title> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script> | |
</head> | |
<body> | |
<canvas width="1400" height="800"></canvas> | |
<script type="text/javascript"> | |
var canvas = document.querySelector("canvas"), | |
context = canvas.getContext("2d"), | |
width = canvas.width, | |
height = canvas.height, | |
radius = 2.5, | |
minDistance = 20, | |
maxDistance = 100, | |
minDistance2 = minDistance * minDistance, | |
maxDistance2 = maxDistance * maxDistance; | |
var tau = 2 * Math.PI, | |
n = 1000, | |
particles = new Array(n); | |
for (var i = 0; i < n; ++i){ | |
particles[i] = { | |
x: width * Math.random(), | |
y0: height * Math.random(), | |
v: .1 * (Math.random() - .5) | |
}; | |
} | |
d3.timer(function(elapsed) { | |
context.clearRect(0, 0, width, height); | |
for (var i = 0; i < n; ++i) { | |
for (var j = i + 1; j < n; ++j) { | |
var pi = particles[i], | |
pj = particles[j], | |
dx = pi.x - pj.x, | |
dy = pi.y - pj.y, | |
d2 = dx * dx + dy * dy; | |
if (d2 < maxDistance2) { | |
context.globalAlpha = d2 > minDistance2 ? (maxDistance2 - d2) / (maxDistance2 - minDistance2) : 1; | |
context.beginPath(); | |
context.moveTo(pi.x, pi.y); | |
context.quadraticCurveTo( | |
(pj.x - pi.x) / 2 + Math.min(pj.x, pi.x), | |
(Math.max(pi.y, pj.y) - Math.min(pi.y, pj.y)) / 2 + Math.min(pj.y, pi.y) + 5, | |
pj.x, | |
pj.y); | |
context.stroke(); | |
} | |
} | |
} | |
context.globalAlpha = 0.8; | |
for (var i = 0; i < n; ++i) { | |
var p = particles[i]; | |
p.y = p.y0 + elapsed * p.v; | |
if (p.y > height + maxDistance) p.x = width * Math.random(), p.y0 -= height + 2 * maxDistance; | |
else if (p.y < -maxDistance) p.x = width * Math.random(), p.y0 += height + 2 * maxDistance; | |
context.beginPath(); | |
var scaleFactor = (p.v * 10 + 0.6) * 2.5; | |
var dotRadius = p.v > 0 ? radius * scaleFactor : radius / scaleFactor; | |
context.arc(p.x, p.y, dotRadius, 0, tau); | |
context.fill(); | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment