canvas標籤clock(時鐘)案例

貓哥的魚庫發表於2017-12-08

這裡寫圖片描述

<!doctype html>
<html>
<head>
	<meta charset="utf-8">
</head>
<body>
	<canvas id="canvas" width="500" height="500" >
			您的瀏覽器不支援canvas標籤,無法看到時鐘
	</canvas>
	<script>
		var canvas=document.getElementById("canvas");
		var cxt=canvas.getContext("2d");
		
		function drawClock(){
		cxt.clearRect(0,0,500,500);
		var now=new Date();
		var sec=now.getSeconds();
		var min=now.getMinutes();
		var hour=now.getHours();
		hour=hour+min/60;
		hour=hour>12?hour-12:hour;
		
		cxt.beginPath();
		cxt.lineWidth=5;
		cxt.strokeStyle="blue";
		cxt.arc(250,250,200,0,2*Math.PI,false);
		cxt.stroke();
		cxt.closePath();
		
		for(var i=0;i<12;i++){
		cxt.beginPath();
		cxt.save();
		cxt.strokeStyle="black";
		cxt.lineWidth=5;
		cxt.translate(250,250);
		cxt.rotate(i*30*Math.PI/180);
		cxt.moveTo(0,-170);
		cxt.lineTo(0,-190);
		cxt.stroke();	
		cxt.restore();
		cxt.closePath();
		}
		
		for(var i=0;i<60;i++){
		cxt.beginPath();
		cxt.save();
		cxt.strokeStyle="black";
		cxt.lineWidth=3;
		cxt.translate(250,250);
		cxt.rotate(i*6*Math.PI/180);
		cxt.moveTo(0,-180);
		cxt.lineTo(0,-190);
		cxt.stroke();	
		cxt.restore();
		cxt.closePath();
		}
		
		cxt.beginPath();
		cxt.save();
		cxt.strokeStyle="black";
		cxt.lineWidth=5;
		cxt.translate(250,250);
		cxt.rotate(hour*30*Math.PI/180);
		cxt.moveTo(0,-140);
		cxt.lineTo(0,10);
		cxt.stroke();	
		cxt.restore();
		cxt.closePath();
		
		cxt.beginPath();
		cxt.save();
		cxt.strokeStyle="black";
		cxt.lineWidth=3;
		cxt.translate(250,250);
		cxt.rotate(min*6*Math.PI/180);
		cxt.moveTo(0,-160);
		cxt.lineTo(0,15);
		cxt.stroke();	
		cxt.restore();
		cxt.closePath();
		
		cxt.beginPath();
		cxt.save();
		cxt.strokeStyle="red";
		cxt.lineWidth=1.5;
		cxt.translate(250,250);
		cxt.rotate(sec*6*Math.PI/180);
		cxt.moveTo(0,-168);
		cxt.lineTo(0,20);
		cxt.stroke();	
		cxt.restore();
		cxt.closePath();
				
		cxt.beginPath();
		cxt.strokeStyle="red";
		cxt.fillStyle="#bbb";
		cxt.lineWidth=2;
		cxt.arc(250,250,5,0,2*Math.PI,false);
		cxt.stroke();	
		cxt.fill();
		cxt.restore();
		cxt.closePath();
		
		cxt.beginPath();
		cxt.save();
		cxt.strokeStyle="red";
		cxt.lineWidth=2;
		cxt.translate(250,250);
		cxt.rotate(sec*6*Math.PI/180);
		cxt.arc(0,-150,5,0,2*Math.PI,false);
		cxt.stroke();	
		cxt.fill();
		cxt.restore();
		cxt.closePath();
		
		cxt.beginPath();
		cxt.fillStyle="red";
		cxt.font="30px 楷體"
		cxt.fillText("焦作時間",200,320);
		cxt.closePath();
		}
		setInterval(drawClock,1000)
			
	</script>
</body>
</html>

相關文章