[tinkering] is it Fall yet?

The calendar says no, but the temperature and my canvas tag say yes! Here is a toast to my favorite season of the year. Dark beer, hoodies, crisp air, and colorful trees!


mouse over to draw tree. mouse’s x controls angle, mouse’s y controls recursion

This is actually just a simple drawing exercise using fractals (simpler than you might think!). It’s a canvas tag, with a little bit of JS to handle the drawing.

Let’s take a look at the code:

(function(){
	var wid=500, hgt=350, lvls=8, seglen=40, segs=0, lvs=0, ang=.4, cnvs=document.getElementById('drawhere_trees'), cx=cnvs.getContext('2d'); 
	var bclrs=['#897500','#5c4800', '#725e00', '#412d00'];
	var lclrs=['#CC0000', '#993300', '#FF6B2A', '#FFAD0B', '#AF8E2A'];
	
	cx.lineCap = 'round';
	cnvs.addEventListener('mousemove', handleMouseMove);
	
	function form(x, y, ang, count, aa, ab) {
		segs++;
		var len=seglen*(count/lvls)>>0, nx = x+len*Math.cos(ang), ny = y+len*Math.sin(ang);
		cx.strokeStyle = bclrs[segs%bclrs.length];
		cx.lineWidth = count;
		cx.beginPath();
		cx.moveTo(x,y);
		cx.lineTo(nx, ny)
		cx.stroke();
		cx.closePath();
		
		if(count > 1) {
			form(nx, ny, ang+aa, count-1, aa, ab);
			form(nx, ny, ang+ab, count-1, aa, ab);
		} else {
			cx.beginPath();
			cx.fillStyle = lclrs[lvs%lclrs.length];
			cx.arc(nx, ny, 5, ang, ang+Math.PI);
			cx.fill()
			cx.closePath()
			lvs++;
		}
	}
	
	form(wid/2, hgt*.9, -Math.PI/2, lvls, ang, -ang);
	
	function handleMouseMove(e) {
		cx.clearRect(0,0,wid,hgt);
		segs = 0, lvs = 0, ang = e.clientX/wid/2;
		form(wid/2, hgt*.9, -Math.PI/2, Math.round(lvls*e.clientY/hgt), ang, -ang);
	}
})();

Leave a Reply

Your email address will not be published. Required fields are marked *

*