Skip to content

Instantly share code, notes, and snippets.

@chadedrupt
Last active August 29, 2015 14:03
Show Gist options
  • Save chadedrupt/a3bb5add8a97088a6e3d to your computer and use it in GitHub Desktop.
Save chadedrupt/a3bb5add8a97088a6e3d to your computer and use it in GitHub Desktop.
Chaos Game
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
function chaosGame(width, height, numSamplesMax) {
var corners = [
{
x: width / 2,
y: 0
},
{
x: 0,
y: height
},
{
x: width,
y: height
}
];
function midPoint(a,b) {
return {
x: (a.x + b.x) / 2,
y: (a.y + b.y) / 2
};
}
function randomCorner() {
return corners[Math.floor(Math.random() * corners.length)];
}
function theAlgorithm() {
return currentPoint = midPoint(currentPoint, randomCorner());
}
var numSamples = 0;
var currentPoint = randomCorner();
return function() {
if (++numSamples > numSamplesMax) return;
return theAlgorithm();
};
}
var width = 960,
height = 500;
var iterator = chaosGame(width, height, 20000);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.timer(function() {
for (var i = 0; i < 20; ++i) {
var s = iterator();
if (!s) return true;
svg.append("circle")
.attr("cx", s.x)
.attr("cy", s.y)
.attr("r", 1);
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment