canvas動畫循環

動畫循環是製作動畫效果的基礎,由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();

總結:
首先實現動畫的初始化,然後執行動畫循環(更新,清楚,繪製)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章