html5实现的canvas时钟

html5实现的canvas时针

效果:


html5实现的canvas时钟
 代码:

<!doctype html>
<html>
	<head>
		<title>时钟</title>
	</head>
	<body>
		<canvas width="500" height="500" id="canvas">
			您的浏览器不支持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 hour = now.getHours();
				var minute = now.getMinutes();
				var second = now.getSeconds();
				hour = hour>12?hour-12:hour;
				
				//表盘
				cxt.lineWidth=10;
				cxt.strokeStyle="blue";
				cxt.beginPath();
				cxt.arc(250,250,200,0,Math.PI*2,false);
				cxt.closePath();
				cxt.stroke();
				//时刻度
				for(var i=0;i<12;i++){
					cxt.save();
					cxt.lineWidth=8;
					cxt.strokeStyle="#000";
					cxt.translate(250,250);
					cxt.rotate(i*Math.PI*2/12);
					cxt.beginPath();
					cxt.moveTo(0,-195);
					cxt.lineTo(0,-175);
					cxt.closePath();
					cxt.stroke();
					cxt.restore();
				}
				//分刻度
				for(var i=0;i<60;i++){
					cxt.save();
					cxt.lineWidth=5;
					cxt.strokeStyle="#000";
					cxt.translate(250,250);
					cxt.rotate(i*Math.PI*2/60);
					cxt.beginPath();
					cxt.moveTo(0,-195);
					cxt.lineTo(0,-185);
					cxt.closePath();
					cxt.stroke();
					cxt.restore();
				}
				//时针
				cxt.save();
				cxt.lineWidth=8;
				cxt.strokeStyle="#000";
				cxt.translate(250,250);
				cxt.rotate(hour*(Math.PI*2/12)+minute*((Math.PI*2/12)/60));
				cxt.beginPath();
				cxt.moveTo(0,-145);
				cxt.lineTo(0,15);
				cxt.closePath();
				cxt.stroke();
				cxt.restore();
				//分针
				cxt.save();
				cxt.lineWidth=5;
				cxt.strokeStyle="#000";
				cxt.translate(250,250);
				cxt.rotate(minute*Math.PI*2/60);
				cxt.beginPath();
				cxt.moveTo(0,-165);
				cxt.lineTo(0,20);
				cxt.closePath();
				cxt.stroke();
				cxt.restore();
				//秒针
				cxt.save();
				cxt.lineWidth=3;
				cxt.strokeStyle="#f00";
				cxt.translate(250,250);
				cxt.rotate(second*Math.PI*2/60);
				cxt.beginPath();
				cxt.moveTo(0,-175);
				cxt.lineTo(0,30);
				cxt.stroke();
				cxt.closePath();
				cxt.beginPath();
				cxt.arc(0,0,8,0,Math.PI*2);
				cxt.closePath();
				cxt.fill();
				cxt.stroke();
				cxt.beginPath();
				cxt.arc(0,-145,5,0,Math.PI*2);
				cxt.closePath();
				cxt.fill();
				cxt.stroke();
				cxt.restore();
			}
			drawClock();
			setInterval(drawClock,1000);
		</script>
	</body>
</html>

相关推荐