[tinkering] splotches

Here is another iteration of my first canvas circles post. This one is more like Fall colored acid rain :). This time, we lose the strokes, introduce a handy getRGBA function, and just let the drawing continue on indefinitely (toggleable of course).


Click the canvas to pause/resume the drawing.

The aforementioned color parsing function is a slightly modified version of the one found here. Let’s take a quick look at it:

// clr is a string like #RRGGBB, alpha is decimal b/w 0 and 1
function getRGBA(clr, alpha) {
		hex = clr.substring(1,7);
		return 'rgba(' + parseInt(hex.substring(0,2), 16) + ',' + parseInt(hex.substring(2,4), 16) + ',' + parseInt(hex.substring(4,6), 16) + ',' + alpha + ')';
	}

Here is the complete iteration:

(function(){
	var cnvs, cx, wid, hgt, circles, interval, count, clrs, startTimeout, running;
	
	cnvs = document.getElementById('drawhere_cicles2');
	cx = cnvs.getContext('2d');
	wid = cnvs.width;
	hgt = cnvs.height;
	circles = [];
	count = 0;
	clrs = ['#CC0000', '#993300', '#FF6B2A', '#FFAD0B', '#AF8E2A'];

	cx.fillStyle = 'rgba(255, 255, 255, .15)';
	
	function tick() {
		for( var i = 0, l = circles.length; i < l; i++ ) {
			var t = circles[i];
			if(t.radius > 0) {
				cx.beginPath();
				cx.arc(t.x, t.y, t.radius, 0, 6.28);
				cx.fillStyle = t.fclr;
				cx.fill();
				cx.closePath();
				
				t.radius -= 2;
				t.x += Math.random() * 2 * ((Math.random() > .5) ? 1 : -1);
				t.y += Math.random() * 2 * ((Math.random() > .5) ? 1 : -1);
			} else {
				t.done = true;
			}
		}
		
		for( i = 0; i < circles.length; i++ ) {
			if(circles[i].done) circles.splice(i, 1);
		}
		
		count++
		
		var clr = clrs[count%clrs.length];
		
		circles.push({	x: Math.random() * wid, 
						y: Math.random() * hgt, 
						radius: Math.random() * 60, 
						fclr: getRGBA(clr, .1)});
		
	}
	
	function getRGBA(clr, alpha) {
		hex = clr.substring(1,7);
		return 'rgba(' + parseInt(hex.substring(0,2), 16) + ',' + parseInt(hex.substring(2,4), 16) + ',' + parseInt(hex.substring(4,6), 16) + ',' + alpha + ')';
	}
	
	function stop() {
		running = false;
		clearInterval(interval);
	}
	
	function start() {
		clearTimeout(startTimeout);
		running = true;
		interval = setInterval(tick, 8);
	}
	
	function handleClick() {
		(running) ? stop() : start();
	}
	
	cnvs.addEventListener('click', handleClick, false);
	
	start();
	startTimeout = setTimeout(stop, 2000);

})();

One Response to '[tinkering] splotches'

  1. felix says:

    Very nice! Maybe fade out the canvas slightly each frame, so new splotches ‘pop’ more?

Leave a Reply to felix Cancel reply

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

*