Recursive Sierpinski's Triangle
A simple version of Sierpinski's triangle using a recursive function.
by Jon Eyrick
HTML
<canvas id="canvas_area" height="420" width="500">
</canvas>
JavaScript
//recursive sierpinski's triangle in Canvas
//by Emily Dawn Smith 2013 http://EmilyDawnSmith.com
$(document).ready(function() {
//when you do the math, a perfect equilateral triangle
//will fit nicely in 420 X 500
var h = 420;
var w = 500;
var drawingCanvas=document.getElementById("canvas_area");
var context=drawingCanvas.getContext("2d");
tripinski(context,h,w);
});
//this function draws the first triangle and then
//figures out the second triangles top and left
//before calling the recursive function
function tripinski(context,h,w) {
//first triangle
var xa = w/2;
var ya = 0;
var xb = 0;
var yb = h;
var xc = w;
var yc = h;
draw_triangle(context,xa,ya,xb,yb,xc,yc,"#000");
var top = h/2;
var left = w/4;
triangle(context,h/2,w/2,top,left);
}
//the recursive function will draw the current triangle
//figure out the top left coordinates for the subsequent
//three triangles and call itself three times
function triangle(context,h,w,top,left) {
//find the three points that make up the
//current triangle
var xa = left;
var ya = top;
var xb = left+w;
var yb = top;
var xc = left+(w/2);
var yc = top+h;
//less than 1 pixel width wont be seen so this is
//a good stopping condition
if (w > 1) {
//draw the current triangle
draw_triangle(context,xa,ya,xb,yb,xc,yc,"#fff");
//half the size and determine the top/left for the next
//series of triangles and call the function on those
var new_h = h/2;
var new_w = w/2;
var top_1 = top + new_h;
var left_1 = left - (new_w/2);
var top_2 = top - new_h;
var left_2 = left + (new_w/2);
var top_3 = top + new_h;
var left_3 = left + w - (new_w/2);
triangle(context,new_h,new_w,top_1,left_1);
triangle(context,new_h,new_w,top_2,left_2);
triangle(context,new_h,new_w,top_3,left_3);
}
}
function draw_triangle(context,xa,ya,xb,yb,xc,yc,color)...