MariaSzubski
8/19/2015 - 12:30 AM

One minute arc length animation for countdown timer using HTML5 canvas.

One minute arc length animation for countdown timer using HTML5 canvas.

/* Requires:
	1 canvas (var ringTimer)
*/

var ringTimer = document.getElementById('ringTimer').getContext('2d');
var rSec = 0;
var length_i, endPoint, arcVal;

function drawRingTimer(){
	// ------------------------------------- Reset Canvas
	ringTimer.clearRect(0,0,174,174);

	// ------------------------------------- Draw outer track ring
	ringTimer.beginPath();
	ringTimer.arc (
		87,				// x position
		87,				// y position
		87,				// radius
		0,				// start
		(2 * Math.PI),	// end
		true			// counter-clockwise
	);
	ringTimer.strokeStyle = '#999';
	ringTimer.fillStyle = '#ddd';
	ringTimer.lineWidth = 1;
	ringTimer.stroke();
	ringTimer.fill();

	// ------------------------------------- Draw inner track ring
	ringTimer.beginPath();
	ringTimer.arc (
		87,				// x position
		87,				// y position
		77,				// radius
		0,				// start
		(2 * Math.PI),	// end
		true			// counter-clockwise
	);
	ringTimer.fillStyle = '#fff';
	ringTimer.stroke();
	ringTimer.fill();

	// ------------------------------------- Increment ring length
	/* length change per frame = [ (radian multiplier) / (60 seconds * frames per second) ] * (elapsed seconds) */
	length_i = ( 2 / (60*25) ) * rSec;

	/* count from top of circle) */
	arcVal = 1.5 + length_i;

	/* calculate radians */
	endPoint = arcVal * Math.PI;


	// ------------------------------------- Draw timer ring
	ringTimer.beginPath();
	ringTimer.arc (
		87,					// x position
		87,					// y position
		82,					// radius
		(1.5 * Math.PI),	// start
		endPoint,			// end
		true				// counter-clockwise
	);
	ringTimer.lineWidth = 10;
	ringTimer.strokeStyle = 'teal';
	ringTimer.stroke();
	rSec++;
}

arcAnim = setInterval(drawRingTimer, 40);