random walk
based on bostock's canvas random motion, http://bl.ocks.org/syntagmatic/5107530, but highlights the motion of a single dot in red
by hrabinowitz
HTML
<canvas id="canvas"></canvas>
JavaScript
var num = 20000;
var canvas = document.getElementById("canvas");
var width = canvas.width = 960;
var height = canvas.height = 500;
var ctx = canvas.getContext("2d");
var particles = d3.range(num).map(function(i) {
return [Math.round(width*Math.random()), Math.round(height*Math.random())];
});
d3.timer(step);
function step() {
ctx.fillStyle = "rgba(255,255,255,0.3)";
ctx.fillRect(0,0,width,height);
ctx.fillStyle = "rgba(0,0,0,0.5)";
particles.forEach(function(p, i) {
//p[0] += Math.round(2*Math.random()-1);
//p[1] += Math.round(2*Math.random()-1);
// hr: a gradual drift downward
p[0] += (2.2*Math.random()-1);
p[1] += (2.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, i);
});
};
function drawPoint(p, i) {
if (i==0) {
ctx.fillStyle = "rgb(255,0,0)";
ctx.fillRect(p[0],p[1],3,3);
} else {
ctx.fillStyle = "rgba(0,0,0,0.5)";
ctx.fillRect(p[0],p[1],1,1);
}
};