Chaos Game: Triangle
Using random numbers to build a Sierpinski gasket in JavaScript
by Jeremy Likness
HTML
<canvas id="c" width="300" height="300"></canvas>
JavaScript
(function () {
var c = document.getElementById("c"),
ctx = c.getContext("2d"),
w = c.width,
h = c.height,
rfn = function(b) { return Math.random() * b; },
px = [0, w/2, w],
py = [0, h, h/2],
gx = rfn(w),
gy = rfn(h),
pl = function(x, y) { ctx.fillRect(x, y, 1, 1); },
iter = 0;
i = function() {
pl(gx, gy);
pt = Math.floor(rfn(3));
gx = (gx + px[pt])/2;
gy = (gy + py[pt])/2;
if (++iter < 10000) {
setTimeout(i, 0);
}
};
ctx.fillStyle = "rgba(0,0,0,0.5)";
i();
})();