Sierpinski Triangle

A Sierpinski Triangle implementation using the "chaos game"

by antelopelovefan

HTML

<canvas id="canvas" width="640" height="480">
<p>Your browser doesn't support canvas.</p>
</canvas>

JavaScript

if(typeof console=='undefined')console={log:function(){}};
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var iter = 50000;

var clear = function() { canvas.width = canvas.width; };

var setPixel = function(imageData, point, r, g, b, a) {
    a = typeof a == 'undefined' ? 255 : a;
    i = (point.x + point.y * imageData.width) * 4;
    
    imageData.data[i  ] = r;
    imageData.data[i+1] = g;
    imageData.data[i+2] = b;
    imageData.data[i+3] = a;
};

var rnd = function(maxRange) {
    return Math.floor(Math.random()*maxRange);
};

var midpoint = function(p1, p2) {
    return {x:Math.round((p1.x+p2.x)/2), y:Math.round((p1.y+p2.y)/2)};
};

$(document).ready( function() {    
    var imgd = ctx.createImageData(canvas.width, canvas.height);
    var a,b,c,x;
    var randomStart = false;

    if(randomStart) {
        //Start at a random location
        a = {x: rnd(canvas.width), y:rnd(canvas.width)};
        b = {x: rnd(canvas.width), y:rnd(canvas.width)};
        c = {x: rnd(canvas.width), y:rnd(canvas.width)};
        x = {x: rnd(canvas.width), y:rnd(canvas.width)};
    }else {    
        //Or start at a fixed location
        a = {x:135, y:57};
        b = {x:370, y:203};
        c = {x:220, y:388};
        x = {x:639, y:350};
    }
    
    console.log('a: ' + a.x + ',' + a.y);
    console.log('b: ' + b.x + ',' + b.y);
    console.log('c: ' + c.x + ',' + c.y);
    console.log('x: ' + x.x + ',' + x.y);
    
    setPixel(imgd, a, 255, 0, 0);
    setPixel(imgd, b, 255, 0, 0);
    setPixel(imgd, c, 255, 0, 0);
    setPixel(imgd, x, 255, 0, 0);
    
    for(var i=0; i<iter; i++) {
        var choice = rnd(3);
        if(choice == 0 ) {
             //a
             x = midpoint(a, x);
        }else if(choice == 1) {
             //b   
             x = midpoint(b, x);
        }else if(choice == 2) {
             //c   
             x = midpoint(c, x);
        }
        
        //console.log('Plotting ' + x.x + ',' + x.y);
     ...