HTML5 & Math: the Sierpinski triangle on canvas

Walking (or I may say, fighting through) D. Knut’s book  “Art of programming” I’ve met Pascal’s triangle, besides I also wanted to make something with html5 canvas some time ago. So there was overwhelming desire to illustrate Pascal’s triangle on canvas.

I’ve found quite interesting way of illustrating numeric sequence in this triangle – Sierpinski triangle and so I’ve implemented it. In a nutshell, even numbers are colored in this triangle.

Implementation code:

	<canvas id="pascalCanvas" width="1500" height="1500"></canvas>

	<script>

		function drawPixel(x, y, context) {
			context.fillRect(x, y, 1, 1);
		}

		canvas = document.getElementById("pascalCanvas");
		c = canvas.getContext("2d");

		//some gradient style
		var gradient = c.createLinearGradient(0, 0, 0, canvas.height);
		gradient.addColorStop(0, "#abc");
		gradient.addColorStop(1, "#000");
		c.fillStyle = gradient;
		//c.fillStyle = "#000";

		//Pascal's triangle
		var tr = new Array(canvas.height);
		for (i = 0; i < canvas.height; i++) {
			tr[i] = new Array(canvas.width);
			for (k = 0; k < canvas.width; k++) {
				if (k == 0)
					tr[i][k] = 1;
				else
					tr[i][k] = 0;
			}
		}

		for (i = 1; i < canvas.height; i++) {
			for (k = 1; k < canvas.width; k++) {
				tr[i][k] = (tr[i-1][k-1] + tr[i-1][k]) % 2;
			}
		}

		//draw
		for (i = 0; i < canvas.height; i++) {
			for (k = 0; k < canvas.width; k++) {
				if (tr[i][k] != 0)
				drawPixel(k, i , c);
			}
		}
	</script>

We get this:

Sierpinski triangle on html5 canvas

Sierpinski triangle on html5 canvas

Live demo

PS: Some fun stuff on St. Valentine day:

Sierpinsli valentine on http://xkcd.ru/543/