必要なのはコールバックです:
Circle(ctx, 50, 50, 25, 1000, function () { // animate drawing a circle
Circle(ctx, 150, 50, 25, 1000, function () { // then animate drawing a circle
Line(ctx, 75, 50, 125, 50, 1000, function(){ // then animate drawing a line
alert('done');
});
});
});
円と線のアニメーション描画の簡単な実装を次に示します。
function Circle(context, x, y, radius, dur, callback) {
var start = new Date().getTime(),
end = start + dur,
cur = 0;
(function draw() {
var now = new Date().getTime(),
next = 2 * Math.PI * (now-start)/dur;
ctx.beginPath();
ctx.arc(x, y, radius, cur, next);
cur = Math.floor(next*100)/100; // helps to prevent gaps
ctx.stroke();
if (cur < 2 * Math.PI) requestAnimationFrame(draw); // use a shim where applicable
else if (typeof callback === "function") callback();
})();
}
function Line(context, x1, y1, x2, y2, dur, callback) {
var start = new Date().getTime(),
end = start + dur,
dis = Math.sqrt(Math.pow(x2-x1,2)+Math.pow(y2-y1,2)),
ang = Math.atan2(y2-y1, x2-x1),
cur = 0;
(function draw() {
var now = new Date().getTime(),
next = Math.min(dis * (now-start)/dur, dis);
ctx.beginPath();
ctx.moveTo(x1 + Math.cos(ang) * cur, y1 + Math.sin(ang) * cur);
ctx.lineTo(x1 + Math.cos(ang) * next, y1 + Math.sin(ang) * next);
cur = next;
ctx.closePath();
ctx.stroke();
if (cur < dis) requestAnimationFrame(draw); // use a shim where applicable.
else if (typeof callback === "function") callback();
})();
}
そして、ここに動作中の (Webkit のみ) デモがあります: http://jsfiddle.net/QSAyw/3/