html5學習canvas實例之時鐘

<html>
	<head>
	<title>html5-01</title>
	<meta http-equiv="content-type" content="text/html" charset="utf-8">
	<script language="javascript">
	window.onload=function (){
		var canvas=document.getElementById("canvas");
		var ctx=canvas.getContext('2d');
		drawclock();
		setInterval(drawclock,1000);
		function drawclock(){
		//獲取當前時間
		var mydate=new Date();
		var hour=mydate.getHours();
		var min=mydate.getMinutes();
		var sec=mydate.getSeconds();
		//清理
		ctx.clearRect(0,0,900,800);
		//表部分
		ctx.beginPath();
		ctx.strokeStyle="blue";
		ctx.lineWidth="20";
		ctx.arc(300,200,150,0,360,false);
		ctx.stroke();
		ctx.closePath();
		//畫時針
		for(var i=0;i<12;i++){
			ctx.save();
			ctx.translate(300,200);
			ctx.rotate(i*30*Math.PI/180);
			ctx.lineWidth="7";
			ctx.strokeStyle="#000";
			ctx.beginPath();
			ctx.moveTo(0,-120);
			ctx.lineTo(0,-140);
			ctx.stroke();
			ctx.closePath();
			ctx.restore();		
		}
		//畫秒針錶盤
		for(var i=0;i<60;i++){
			ctx.save();
			ctx.translate(300,200);
			ctx.rotate(i*6*Math.PI/180);
			ctx.lineWidth="3";
			ctx.strokeStyle="#000";
			ctx.beginPath();
			ctx.moveTo(0,-130);
			ctx.lineTo(0,-140);
			ctx.stroke();
			ctx.closePath();
			ctx.restore();		
		}	
		//畫秒針
		ctx.save();
		ctx.translate(300,200);
		ctx.rotate(sec*6*Math.PI/180);
		ctx.strokeStyle="#666";
		ctx.lineWidth="3";
		ctx.beginPath();
		ctx.moveTo(0,10);
		ctx.lineTo(0,-110);
		ctx.stroke();
		ctx.closePath();
	
		ctx.beginPath();
		ctx.arc(0,-80,5,0,360,false);
		ctx.fill();
		ctx.closePath();
		ctx.restore();

		//畫分針
		ctx.save();
		ctx.translate(300,200);
		ctx.rotate(min*6*Math.PI/180);
		ctx.strokeStyle="#666";
		ctx.lineWidth="3";
		ctx.beginPath();
		ctx.moveTo(0,10);
		ctx.lineTo(0,-80);
		ctx.stroke();
		ctx.closePath();
	
		ctx.beginPath();
		ctx.arc(0,-60,5,0,360,false);
		ctx.fill();
		ctx.closePath();
		ctx.restore();

		
		
		//畫時針
		ctx.save();
		ctx.translate(300,200);
		ctx.rotate(hour*30*Math.PI/180);
		ctx.strokeStyle="#666";
		ctx.lineWidth="3";
		ctx.beginPath();
		ctx.moveTo(0,10);
		ctx.lineTo(0,-50);
		ctx.stroke();
		ctx.closePath();

		ctx.beginPath();
		ctx.arc(0,-30,5,0,360,false);
		ctx.fill();
		ctx.closePath();
		ctx.restore();

		ctx.beginPath();
		ctx.arc(300,200,5,0,360,false);
		ctx.fillStyle="#000";
		ctx.fill();
		ctx.closePath();

		
	}

	}
	</script>
	</head>
	<body>
		
		<canvas  id="canvas" width="900" height="800" >
			你的瀏覽器不支持canvas標籤
		</canvas>
	</body>
</html>

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