// fractal fern
// piotr at skowro dot net

var mycanvas;
var context;
var x,y;
var xmax=200, ymax=200;
var i_counter=0;


var onloadFernSaved=window.onload;

window.onload = function() {	
  canvas = document.getElementById('mycanvas');
  if (canvas != null) doFernLoad(canvas);	
  if (onloadFernSaved != null) onloadFernSaved();
}

function doFernLoad(element)
{
  mycanvas = element;
  paintFernInit();
  setTimeout("createCanvas();", 500);  
}

function createCanvas()
{
  context = mycanvas.getContext("2d");
  context.fillStyle="#80E080";
  paintFern();
};


function putPixel(x,y)
{
  if (x>=xmax) return;
  if (y>=ymax) return;

// seems it is slower than fillRect
//  context.beginPath();
//  context.moveTo(x,y);
//  context.lineTo(x+1,y+1);
//  context.stroke();
  context.fillRect(x,y,1,1);
}


function paintFernInit()
{
  x=0;		
  y=0;
  zx=18;	// zoom X
  zy=18;	// zoom Y
  tx=-120;	// transp. x
  ty=-200;	// transp. y  
};

function paintFern()
{
  var a, b, c, d, e, f, r, nx, ny, R;

  i_counter++;
  R= Math.random()*100;	// random 0-100
	
  if (R <= 1) {
    a=0; b=0; c=0; d=0.16; e=0; f=0;
  };
	  
  if ((R >  1) && (R <= 86)) {
    a=0.85; b=0.04; c=-0.04; d=0.85; e=0; f=1.6;
  };
	   
  if ((R > 86) && (R <= 93)) {
    a=0.2; b=-0.26; c=0.23; d=0.22; e=0; f=1.6;
  };

  if ((R > 93) && (R <=100)) {
    a=-0.15; b=0.28; c=0.26; d=0.24; e=0; f=0.44;
  };

  nx= (a * x) + (b * y) + e;
  ny= (c * x) + (d * y) + f;
  x=nx;
  y=ny;

  putPixel(Math.round(Math.abs(tx+x*zx)), 
           Math.round(Math.abs(ty+y*zy)));  		

  if (i_counter<5000) setTimeout("paintFern()", 10);
}

