html5tree.html
Code: Select all
<html>
<head>
<script>
window.onload=draw;
//
function draw()
{
var canvas=document.getElementById('myCanvas');
//
if (canvas.getContext)
{
var tgt=canvas.getContext('2d');
drawFractalTree(tgt);
}
else
{
alert("HTML5 Canvas not available on your browser, try firefox or chrome (v2015-2016+)");
}
}
//
function drawFractalTree(tgt)
{
drawTree(tgt,1800,2000,-90,16);
}
//
function drawTree(tgt,x1,y1,angle,depth)
{
var BRANCH_LENGTH=random(0,20);
//
if (depth!=0)
{
var x2=x1+(cos(angle)*depth*BRANCH_LENGTH);
var y2=y1+(sin(angle)*depth*BRANCH_LENGTH);
drawLine(tgt,x1,y1,x2,y2,depth);
drawTree(tgt,x2,y2,angle-random(10,20),depth-1);
drawTree(tgt,x2,y2,angle+random(10,20),depth-1);
}
}
//
function drawLine(tgt,x1,y1,x2,y2,thickness)
{
tgt.fillStyle='#000';
/*
change the number up for each level you want
as a base color before going to upper branch color
this example uses >0 which means all lines are the first color
which I made black, great to save png files with transparency
*/
//
if(thickness>0)
{
//Brown
//tgt.strokeStyle='rgb(130,120, 92)';
//black
tgt.strokeStyle='rgb(0,0,0)';
}
else
{
//green
tgt.strokeStyle='rgb(30,139,30)';
}
tgt.lineWidth=thickness*1.5;
tgt.beginPath();
tgt.moveTo(x1,y1);
tgt.lineTo(x2,y2);
tgt.closePath();
tgt.stroke();
}
//
function cos(angle)
{
return Math.cos(deg_to_rad(angle));
}
//
function sin(angle)
{
return Math.sin(deg_to_rad(angle));
}
//
function deg_to_rad(angle)
{
return angle*(Math.PI/180.0);
}
//
function random(min,max)
{
return min+Math.floor(Math.random()*(max+1-min));
}
</script>
<style type="text/css">
canvas {border:1px solid white;}
</style>
</head>
<body>
<center>
<canvas id="myCanvas" width="3800" height="2000"></canvas>
</center>
</body>
</html>