Skip to content

Instantly share code, notes, and snippets.

@absurd
Created January 11, 2013 12:58
Show Gist options
  • Save absurd/4510449 to your computer and use it in GitHub Desktop.
Save absurd/4510449 to your computer and use it in GitHub Desktop.
Draws the fractal Sierpinski Triangle on an html5 canvas element via the Chaos Game method.
drawflag = false;
i = -10;
maxi = 1000000;
function toggleDraw() {
button = document.getElementById("button");
drawflag = !drawflag;
if (!drawflag) {
button.innerHTML = "Resume";
} else {
button.innerHTML = "Stop";
canv = document.getElementById("c1");
c = canv.getContext("2d");
counter = document.getElementById("ct");
if (i<=0) {
x = Math.random()*canv.width | 0;
y = Math.random()*canv.height | 0;
p = [x,y];
}
equiheight = Math.sqrt(3*canv.height*canv.height/4.);
equivertices = [[canv.width/2,canv.height/2-equiheight/2],
[0,canv.height/2+equiheight/2],
[canv.width,canv.height/2+equiheight/2]];
draw();
}
}
function draw() {
if (drawflag) {
counter.innerHTML = i;
p = chaosgame(equivertices,p,0.5);
if (i > 0) { // burn the first few
c.fillRect(p[0],p[1],1,1);
}
i += 1;
if (i < maxi) {
setTimeout("draw()",1);
}
}
}
function chaosgame(vertices,p,frac) {
/*Takes a list of vertices, each vertex
tuple of the form (x,y), a 2-tuple p of
the same form, and a floating point frac.
Randomly selects a vertex and returns
the point that is the frac fraction of
the way between the vertex and point p.
*/
var v_index = Math.min(Math.floor(Math.random()*vertices.length),vertices.length-1);
var vertex = vertices[v_index];
var new_x = (vertex[0] + p[0]) * frac;
var new_y = (vertex[1] + p[1]) * frac;
return [new_x,new_y];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment