JavaScript/Canvas Spinning ProgressIndicator Class

In my last post, I showed a simple example of using the canvas element to draw rounded corners. Remedial class is over… here’s an example of more exciting… Below are links to a canvas element used to create an OS X-style indeterminate spinning progress indicator.

This is actually a re-usable JavaScript class called ProgressIndicator.

Usage requires a little HTML and a little JavaScript. In your HTML include the JS class in the head of your document:


<script type="text/javascript" src="ProgressIndicator.js"></script>

And declare a canvas element with width and height attributes in the body:


<canvas id="c" width="200" height="200"></canvas>

In JavaScript, execute this code after page load:


// get ref to canvas element on the page
var c = document.getElementById("c");

// pass canvas ref to the constructor
var prog = new ProgressIndicator(c);

//make the progress indicator aqua (or any other color)
prog.setRGB(0,255,255);

// begin the animation
prog.startAnimation();
	...

// stop animation later
prog.stopAnimation();

Note that you can also dig into the source code, tweak some of the class’s private variables and create all sorts of cool effects by changing the number of bars or the bar corner radius.


About this entry