1. 程式人生 > >Jscript動畫系列(1)-----用JS在Canvas上畫一個小球

Jscript動畫系列(1)-----用JS在Canvas上畫一個小球

最近在學習JS動畫,有一些心的同大家分享!由於前期內容比較少,樣式什麼的就寫在Html檔案裡了!

首先(Index.html)

<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<title>this is one Ball</title>
	</head>
	<body>
		<canvas id="canvas" width="400" height="400"style="background-color:#000></canvas>
		<script src="Ball.js"></script>
		<script>
			window.onload=function(){
				//Our code here...
			};
		</script>
	</body>
</html>

上面的這段Html程式碼就相當於一個模板,後面基本不會有太大的變化,主要的內容在<srcipt>標籤裡。

接下來我們會單獨建一個JS檔案,這個檔案主要是一個球類,這個類擁有這個球的一些屬性比如半徑,顏色,位置(x,y)等,還有一些方法。

檔名(Ball.js)

//定義一個小球類Ball
function Ball (radius,color){
	if(radius === undefined){radius=40;}
	if(color === undefined){color="#ff0000";}
	this.x=0;//x軸座標
	this.y=0;//y軸座標
	this.radius=radius;//半徑
	this.vx = 0;
	this.vy = 0;
	this.rotation=0;//旋轉角度
	this.color=color;//utils.parseColor(color);
	this.lineWidth=1;
}
//小球的繪製方法
Ball.prototype.draw=function(context){
	context.save();//先儲存一下當前畫布狀態
	context.translate(this.x,this.y); //將座標原點設定為(x,y),預設
	context.rotate(this.rotation); //旋轉當前繪圖
	context.lineWidth=this.lineWidth; //畫筆粗細
	context.fillStyle=this.color;  //圓圈內填充的顏色
	context.beginPath();  //開始一條繪畫路徑
	context.arc(0,0,this.radius,0,(Math.PI*2),true); //畫一個圓
	context.closePath();  //結束當前路徑
	context.fill();  //開始填充
	//若有邊框
	if(this.lineWidth>0){
		context.stroke(); //繪製邊框
	}
	context.restore();//將繪圖狀態置為儲存值。
};

說明:

  1. 註釋只是簡略的說明作用,想深入瞭解請自行百度。
  2. Ball.js檔案可單獨儲存要用時使用<script src="Ball.js"></script> 引用即可
  3. 現在只是一個最簡單的圓,後面還會新增一些其他的屬性和方法,比如(速度屬性,密度屬性,發光效果)等。

現在開始寫<script>裡面的內容

window.onload=function(){
	var canvas = document.getElementById('canvas');
		context = canvas.getContext('2d');
	var ball=new Ball();  //建立一個Ball
        ball.x=canvas.width/2;  //設定其位置(canvas的中央)
        ball.y=canvas.height/2;
	ball.draw(context);  //呼叫Ball的draw方法
};

這樣就很簡單的在canvas上畫了一個圓;