[tinkering] circles

Repeating circles without clearing the canvas. It’s like fall colored soft-serve.


Click anywhere on the canvas to restart the drawing.

The code is pretty simple. Basic steps are:

  • create a an array of your circle data
  • iterate over the array on an interval to update each circle’s attributes
  • draw each circle on every tick – forget about clearing the canvas
  • stop the interval once all circles are complete.

Let’s take a look:

(function(){
	var cnvs, cx, wid, hgt, circles, interval, count, clrs;
	
	cnvs = document.getElementById(‘drawhere_cicles1’);
	cx = cnvs.getContext(‘2d’);
	wid = cnvs.width;
	hgt = cnvs.height;
	circles = [];
	count = 30;
	clrs = [‘#CC0000’, ‘#993300’, ‘#FF6B2A’, ‘#FFAD0B’, ‘#AF8E2A’];
	
	cx.fillStyle = ‘rgba(255, 255, 255, .7)’;
	
	function draw() {
		cx.clearRect(0, 0, wid, hgt);
		
		for( var i = 0; i < count; i++ ) {
			circles.push({	x: Math.random() * wid, 
							y: Math.random() * hgt, 
							radius: Math.random() * 400, 
							color: clrs[i%clrs.length]});
		}
		
		interval = setInterval(tick, 8);
	}
	
	function tick() {
		for( var i = 0, l = circles.length; i < l; i++ ) {
			var t = circles[i];
			if(t.radius > 0) {
				cx.beginPath();
				cx.strokeStyle = t.color;
				cx.arc(t.x, t.y, t.radius, 0, 6.28);
				t.radius -= 2;
				t.x += Math.random() * 2 * ((Math.random() > .5) ? 1 : -1);
				t.y += Math.random() * 2 * ((Math.random() > .5) ? 1 : -1);
				cx.stroke();
				cx.fill();
				cx.closePath();
			} else {
				t.done = true;
			}
		}
		
		for( i = 0; i < circles.length; i++ ) {
			if(circles[i].done) circles.splice(i, 1);
		}
		
		if( circles.length == 0) {
			clearInterval(interval);
		}
	}
	
	draw();
	
	cnvs.addEventListener(‘click’, draw, false);
})();

Leave a Reply

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

*