nextwebgen.com

The Next Generation Web Now

Canvas Loading Indicator for the iPhone and beyond

Filed under: Web 2.0 News — Dion Almaer at 8:30 am on Saturday, September 29, 2007

Adam van den Hoven wrote a Canvas Loading Indicator after he realised that animated gifs and the iPhone didn’t mesh.

First he wrote the basic spinner:

JAVASCRIPT:

  1.  
  2. function getLoading(context, bars, center, innerRadius, size, color) {
  3. var animating = true,
  4.     currentOffset = 0;
  5.  
  6. function makeRGBA(){
  7.     return “rgba(” + [].slice.call(arguments, 0).join(“,”) + “)”;
  8. }
  9. function drawBlock(ctx, barNo){
  10.     ctx.fillStyle = makeRGBA(color.red, color.green, color.blue, (bars+1-barNo)/(bars+1));
  11.     ctx.fillRect(-size.width/2, 0, size.width, size.height);
  12. }
  13. function calculateAngle(barNo){
  14.     return 2 * barNo * Math.PI / bars;
  15. }
  16. function calculatePosition(barNo){
  17.     angle = calculateAngle(barNo);
  18.     return {
  19.         y: (innerRadius * Math.cos(-angle)),
  20.         x: (innerRadius * Math.sin(-angle)),
  21.         angle: angle
  22.     };
  23. }
  24. function draw(ctx, offset) {
  25.     clearFrame(ctx);
  26.     ctx.save();
  27.     ctx.translate(center.x, center.y);
  28.     for(var i = 0; i<bars; i++){
  29.         var curbar = (offset+i) % bars,
  30.             pos = calculatePosition(curbar);
  31.         ctx.save();
  32.         ctx.translate(pos.x, pos.y);
  33.         ctx.rotate(pos.angle);
  34.         drawBlock(context, i);
  35.         ctx.restore();
  36.     }
  37.     ctx.restore();
  38. }
  39. function clearFrame(ctx) {
  40.     ctx.clearRect(0, 0, ctx.canvas.clientWidth, ctx.canvas.clientHeight);
  41. }
  42. function nextAnimation(){
  43.     if (!animating) {
  44.         return;
  45.     };
  46.     currentOffset = (currentOffset + 1) % bars;
  47.     draw(context, currentOffset);
  48.     setTimeout(nextAnimation, 50);
  49. }
  50. nextAnimation(0);
  51. return {
  52.     stop: function (){
  53.         animating = false;
  54.         clearFrame(context);
  55.     },
  56.     start: function (){
  57.         animating = true;
  58.         nextAnimation(0);
  59.     }
  60. };
  61. }
  62.  

And then to use it:

JAVASCRIPT:

  1.  
  2. var controller = getLoading(canvas.getContext(“2d”), 9, {x:100, y:100}, 10, {width: 2, height:10}, {red: 0, green: 17, blue: 58});
  3.  
Share and Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
  • blogmarks
  • del.icio.us
  • De.lirio.us
  • digg
  • NewsVine
  • YahooMyWeb

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>