Recursive Sierpinski Triangle in HTML5

I’ve made this recursive Sierpinski triangle written using HTML5’s canvas and JavaScript. Next I’m going to try to make a 3D version in WebGL.

This is the HTML5 side of the code. All it contains is a canvas.

<html>
    <body>
        <canvas width="200" height="200" id="canvas"/>
    </body>
</html>

Here is my JavaScript code. I coded this together pretty quick so it’s not the most elegant code but it contains two functions, init() and draw(). The function init() takes in a number for the depth of this fractal and starts the recursive draw function to draw the triangles lines. The end result will look something like this.

Depth of 2 Depth of 3
<script>
var cv = document.getElementById('canvas').getContext('2d');
function draw(cv, depth, pt1, pt2, pt3){
	if(depth > 0){
		if(depth % 2 == 0)
			cv.fillStyle = "white";
		else
			cv.fillStyle = "gold";
			
		cv.beginPath();
	
		cv.moveTo(pt1[0], pt1[1]);
		cv.lineTo(pt2[0], pt2[1]);
		cv.lineTo(pt3[0], pt3[1]);
		
		cv.closePath();
		cv.fill();
		cv.strokeStyle = "rgb(0,128,0)";
		cv.lineWidth = 0.5;
		cv.stroke();
	
		// Finding mid points
		var pt1_pt2 = new Array( (pt1[0] + pt2[0]) / 2,
					         (pt1[1] + pt2[1]) / 2 ); 
		var pt2_pt3 = new Array( (pt2[0] + pt3[0]) / 2,
					         (pt2[1] + pt3[1]) / 2 );
		var pt3_pt1 = new Array( (pt3[0] + pt1[0]) / 2,
					         (pt3[1] + pt1[1]) / 2 );
		
		// Recursive action
		draw(cv, depth - 1, pt1, pt1_pt2, pt3_pt1);
		draw(cv, depth - 1, pt2, pt2_pt3, pt1_pt2);
		draw(cv, depth - 1, pt3, pt3_pt1, pt2_pt3);
	}
}

function init(depth){
    draw(cv, depth, new Array(20,160), new Array(180,160), new Array(100,20));
}

init(2);

</script>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s