动画循环是制作动画效果的基础,由3个部分组成。
先后是更新操作,清楚操作,绘制操作,并且会不断重复的进行。
如下有demo代码,有助于更好地理解.
<canvas id="canvas" width="500" height="500" style="background-color:red;"></canvas>
<script>
var canvas=document.getElementById('canvas');
var context=canvas.getContext('2d');
var circle={ //创建一个圆形对象
x:250,
y:250,
radius:50,
direction:'right',
move:function(){
if(this.direction==='right'){
if(this.x<=440)
{
this.x+=5;
}
else
{
this.direction='left';
}
}else{
if(this.x>=60)
{
this.x-=5;
}
else
{
this.direction='right';
}
}
},
draw:function(){
context.beginPath();
context.arc(this.x,this.y,this.radius,0,2*Math.PI,false);
context.closePath();
context.fillStyle='blue';
context.fill();
}
};
function animation()
{
circle.move(); //更新
context.clearRect(0,0,canvas.width,canvas.height); //清除
circle.draw(); //绘制
requestAnimationFrame(animation); //循环
}
circle.draw();
animation();
总结:
首先实现动画的初始化,然后执行动画循环(更新,清楚,绘制)。