[英]How can I execute different animations one by one within a HTML5 Canvas context
我正在創建一個動畫,該動畫繪制一個像“ O-O”形狀的畫布。 動畫應首先進行動畫處理,以在左側繪制圓,然后在右側繪制圓,最后在兩者之間建立連接。
我可以畫一個圓,但我想知道如何一一畫出三個元素,而不是將三個元素畫在一起。
偽代碼:
window.onload = draw;
function draw(){
drawcircle();
}
function drawcircle(){
draw part of circle
if( finish drawing){
clearTimeout
}
else{
setTimeout(drawcircle());
}
但是,如果我先在draw()函數之后運行另一個drawcircle函數。 兩個圓圈同時繪制,而不是一個一個地繪制。 有沒有一種方法可以逐個繪制每個元素? 非常感謝
您可能真正想要使用的是requestAnimationFrame。 然后,您可以完全省去setTimeout。 http://paulirish.com/2011/requestanimationframe-for-smart-animating/是一篇很棒的博客文章,可幫助您入門。
您想要的是回調 :
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/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.