[英]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.