Sierpinski’s Gasket

HTML 5/JS (Javascript)

<canvas id="sierpinski_canvas" width="750" height="750" style="border:1px solid #888;"></canvas>

<script>
var canvas = document.getElementById("sierpinski_canvas");
var canvasInfo = document.getElementById("sierpinski_canvas").getBoundingClientRect();
var canvasWidth = canvasInfo.width;
var canvasHeight = canvasInfo.height;
var ctx = canvas.getContext("2d");
var rectDim = 750;
var rectMinSize = 7;

function drawGasket(x, y, rectDim) {
    if (rectDim <= rectMinSize) {
            var randomColor = Math.floor(Math.random()*16777215).toString(16);
            ctx.fillStyle = "#" + randomColor;
	    ctx.fillRect(x, y, rectDim, rectDim);
    }
    else {
	    var newRectDim = rectDim / 2;
	    drawGasket(x, y, newRectDim);
	    drawGasket(x + newRectDim, y, newRectDim);
	    // drawGasket(x, y + newRectDim, newRectDim);
	    drawGasket(x + newRectDim, y + newRectDim, newRectDim);
    }
};
drawGasket(0, 0, rectDim);
</script>