Skip to content

Instantly share code, notes, and snippets.

@paulgb
Forked from wrr/index.html
Created February 10, 2013 20:56
Show Gist options
  • Save paulgb/4751028 to your computer and use it in GitHub Desktop.
Save paulgb/4751028 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<!-- By Jan Wrobel (http://mixedbit.org) -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Random walk</title>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://raw.github.com/mbostock/d3/master/lib/colorbrewer/colorbrewer.js"></script>
<style type="text/css">
body {
background: #222;
}
</style>
</head>
<body>
<button type="button" onclick="faster();">Faster!</button>
<script type="text/javascript">
function init_array(size, init_v) {
var result = [];
for (i = 0; i < size; i += 1) {
result.push(init_v);
}
return result;
}
var GRID = 5,
WALK_H = 280,
WALK_W = 2 * WALK_H,
PLOT_H = WALK_H / 2,
POINT_R = 4,
delay = 100,
result_cnt = init_array(WALK_W / GRID, 0),
svg = d3.select("body").append("svg:svg")
.attr("width", WALK_W)
.attr("height", WALK_H + PLOT_H + POINT_R),
PALETE = colorbrewer.Oranges[9].reverse();
$('button').attr('disabled', false);
walk(WALK_W / 2, 0);
function faster() {
if (delay > 20) {
delay -= 20;
} else {
delay = 0;
$('button').attr('disabled', true);
}
}
function append_result(final_x) {
var result_idx = final_x / GRID;
svg.append("svg:circle")
.attr("cx", final_x)
.attr("cy", WALK_H + POINT_R)
.attr("r", POINT_R)
.style("fill", "aliceblue")
.style("opacity", 0.85)
.transition()
// Move the result point to the bottom of the plot.
.attr("cy", WALK_H + PLOT_H - 2 * POINT_R * result_cnt[result_idx] )
.duration(3000);
result_cnt[result_idx] += 1;
}
function walk(x, y) {
var x_end, y_end = y + GRID;
if (Math.random() < 0.5) {
x_end = x + GRID;
} else {
x_end = x - GRID;
}
line = svg.select('line[x1="' + x + '"][x2="' + x_end + '"]'+
'[y1="' + y + '"][y2="' + y_end + '"]');
if (line.empty()) {
// Create a new line segment
svg.append("svg:line")
.attr("x1", x)
.attr("y1", y)
.attr("x2", x_end)
.attr("y2", y_end)
.style("stroke", PALETE[0])
.style("stroke-width", 2)
.data([0]);
} else {
// or alter color of an existing line.
var color_idx = Math.min(line.data() + 1, PALETE.length - 1);
line.style('stroke', PALETE[color_idx])
.datum(color_idx)
}
if (y_end >= WALK_H) {
// End reached.
append_result(x_end);
x_end = WALK_W / 2;
y_end = 0;
}
window.setTimeout(function() {
walk(x_end, y_end);
}, delay);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment