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>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值