Create tree with branches transparent png html canvas

Post Reply
darknkreepy3#
Site Admin
Posts: 253
Joined: Tue Oct 27, 2009 9:33 pm

Create tree with branches transparent png html canvas

Post by darknkreepy3# »

I needed to create quick 2d branches for a graphic design I was layering in illustrator and photoshop, and really didn't want to hand draw thousands of branches. I found an HTML5 script that randomizes branches 10-20° and so I made it black and maximized the script to generate a 4K level image that you can right click and save as a transparent PNG. If you want to change the colors during the distance of the tree's branches you can, or just save them all black or white, whatever in HEX you like, and then layer them in photoshop as well. Even import into illustrator directly.

Image

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>
Post Reply