Triangles

by sikuda

HTML

<canvas id="myCanvas" width="800" height="640" style="border:1px solid #d3d3d3;">Your browser does not support the HTML5 canvas tag.</canvas>

JavaScript

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var timeFrame = 50;
var width  = 600,
    height = 600;
var step = 0;
var points = [ new point(width/2, height*(1 - Math.sqrt(3)/2 ) ), 
               new point(0, height),
               new point(width, height)
             ];
var new_points = [];

run();

function run() {
    var beginTime = new Date();

    draw();
    dostep();
    step += 1;
    var endTime = new Date();
    endTime = endTime.getTime() - beginTime.getTime();
    if (endTime !== 0) endTime = 1000 / endTime;
    else endTime = "Max1000";
    ctx.fillText("Step: "+step+" Visible FPS:" + (1000 / timeFrame) + " Max FPS: " + endTime, 0, 10);

    if( step < 8) {
        timeFrame =  2*timeFrame / Math.sqrt(step);
        setTimeout( function () { run(); }, timeFrame);
    }    
}

function dostep(){
    new_points = [];
    for(var i=0; i < points.length; i++){
        var new_point;
        if( i == points.length-1 ){
            new_point = new point( (points[points.length-1].x + points[0].x)/2, (points[points.length-1].y + points[0].y)/2);    
        }    
        else {
            new_point = new point( (points[i+1].x + points[i].x)/2, (points[i+1].y + points[i].y)/2);    
        }    
        new_points.push(points[i], new_point);
        //ctx.fillText("x: "+new_points.length, 10, 100);
    }
    points = new_points;
}

function draw(){
    ctx.clearRect(0, 0, width, height);
    //ctx.beginPath();
    //ctx.fillStyle = "x000000";
    var k = Math.pow(2,step);
        for(var i = 0; i < k; i++){
            ctx.beginPath();
            ctx.moveTo(points[i].x, points[i].y);
            ctx.lineWidth = 1;
            ctx.strokeStyle = 'red';
            ctx.lineTo(points[i+k].x, points[i+k].y);
            ctx.stroke();
            
            ctx.beginPath();
            ctx.moveTo(points[i+k].x, points[i+k].y);
            ctx.strokeStyle = 'green';
            ctx.lineTo(points[i+2*k].x, points[i+2*k].y);
     ...