Saturday, September 29th, 2007
Canvas Loading Indicator for the iPhone and beyond
<p>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:
-
-
function getLoading(context, bars, center, innerRadius, size, color) {
-
var animating = true,
-
currentOffset = 0;
-
-
function makeRGBA(){
-
return "rgba(" + [].slice.call(arguments, 0).join(",") + ")";
-
}
-
function drawBlock(ctx, barNo){
-
ctx.fillStyle = makeRGBA(color.red, color.green, color.blue, (bars+1-barNo)/(bars+1));
-
ctx.fillRect(-size.width/2, 0, size.width, size.height);
-
}
-
function calculateAngle(barNo){
-
return 2 * barNo * Math.PI / bars;
-
}
-
function calculatePosition(barNo){
-
angle = calculateAngle(barNo);
-
return {
-
y: (innerRadius * Math.cos(-angle)),
-
x: (innerRadius * Math.sin(-angle)),
-
angle: angle
-
};
-
}
-
function draw(ctx, offset) {
-
clearFrame(ctx);
-
ctx.save();
-
ctx.translate(center.x, center.y);
-
for(var i = 0; i<bars; i++){
-
var curbar = (offset+i) % bars,
-
pos = calculatePosition(curbar);
-
ctx.save();
-
ctx.translate(pos.x, pos.y);
-
ctx.rotate(pos.angle);
-
drawBlock(context, i);
-
ctx.restore();
-
}
-
ctx.restore();
-
}
-
function clearFrame(ctx) {
-
ctx.clearRect(0, 0, ctx.canvas.clientWidth, ctx.canvas.clientHeight);
-
}
-
function nextAnimation(){
-
if (!animating) {
-
return;
-
};
-
currentOffset = (currentOffset + 1) % bars;
-
draw(context, currentOffset);
-
setTimeout(nextAnimation, 50);
-
}
-
nextAnimation(0);
-
return {
-
stop: function (){
-
animating = false;
-
clearFrame(context);
-
},
-
start: function (){
-
animating = true;
-
nextAnimation(0);
-
}
-
};
-
}
-
And then to use it:
-
-
var controller = getLoading(canvas.getContext("2d"), 9, {x:100, y:100}, 10, {width: 2, height:10}, {red: 0, green: 17, blue: 58});
-
Related Content:











Adam, doesn’t see to have a demo currently, so for those who want immediate visual stimuli, I have thrown the example code up: Canvas Loading Example.
Pretty cool stuff, I didn’t know the iphone had Canvas support, opens up a whole new world of possibilities.
I must be missing something here. A while back, I wrote a small app for the iPhone and it uses an animated GIF stolen from this page. Works fine on my iPhone…
Good find.
Canvas for displaying animated GIFs…!
Makes me think about the time I nuked a couple of insects in my backyard… ;)
Still impressive though :)
Cool stuff.
thanks good post
Canvas is cool, but take a look at my approach using SVG animations. Works fine on every Webkit, including MobileSafari on the iPhone:
http://nickynubbel.blogspot.com/2010/06/coole-iphone-kompatible-loading.html, however this post is in German.
Use Google translater instead: http://translate.google.de/translate?u=http%3A%2F%2Fnickynubbel.blogspot.com%2F2010%2F06%2Fcoole-iphone-kompatible-loading.html&sl=de&tl=en&hl=&ie=UTF-8