html5用canvas画一个时钟


效果如图,秒针可以动态走动的  直接上源码,比较简单


<!doctype html>
<html>
	<head>
		<title></title>
	</head>
	<body>
		<canvas id="clock" width="500" height="500" >your brower do not support canvas</canvas>
		<script >
		var clock=document.getElementById('clock');
		var cxt=clock.getContext('2d');
		function drawClock(){
			// clear the canvas
			cxt.clearRect(0,0,500,500);
			// get the current time 
			var now = new Date();
			var sec=now.getSeconds();
			var min=now.getMinutes();
			var hor=now.getHours();
			hor=hor+min/60;
			hor=hor>12?hor-12:hor;
			//circle
			cxt.lineWidth=9;
			cxt.strokeStyle="#699"
			cxt.beginPath();
			cxt.arc(250,250,200,0,360,false);
			cxt.closePath();
			cxt.stroke();

			//Scale
				// the scale of hour
				for(var i=0;i<12;i++){
					cxt.save();
					cxt.lineWidth=7;
					cxt.strokeStyle="#099";
					cxt.translate(250,250);
					cxt.rotate(i*Math.PI/6);
					cxt.beginPath();
					cxt.moveTo(0,-175);
					cxt.lineTo(0,-195);
					cxt.closePath();
					cxt.stroke();
					cxt.restore();
				}
				// the scale of minute
				for(var i=0;i<60;i++){
					if(i%5!=0){
						cxt.save();
						cxt.lineWidth=5;
						cxt.strokeStyle="#099";
						cxt.translate(250,250);
						cxt.rotate(i*Math.PI/30);
						cxt.beginPath();
						cxt.moveTo(0,-185);
						cxt.lineTo(0,-195);
						cxt.closePath();
						cxt.stroke();
						cxt.restore();
					}
					
				}
			//hour
			cxt.save();
			cxt.lineWidth=7;
			cxt.strokeStyle="#099";
			cxt.translate(250,250);
			cxt.rotate(hor*30*Math.PI/180);
			cxt.beginPath();
			cxt.moveTo(0,-130);
			cxt.lineTo(0,10);
			cxt.closePath();
			cxt.stroke();
			cxt.restore();
			//minute
			cxt.save();
			cxt.lineWidth=7;
			cxt.strokeStyle="#099";
			cxt.translate(250,250);
			cxt.rotate(min*6*Math.PI/180);
			cxt.beginPath();
			cxt.moveTo(0,-155);
			cxt.lineTo(0,10);
			cxt.closePath();
			cxt.stroke();
			cxt.restore();
			//second
			cxt.save();
			cxt.lineWidth=7;
			cxt.strokeStyle="#099";
			cxt.translate(250,250);
			cxt.rotate(sec*6*Math.PI/180);
			cxt.beginPath();
			cxt.moveTo(0,-175);
			cxt.lineTo(0,20);
			cxt.closePath();
			cxt.stroke();
			//the focus
			cxt.beginPath();
			cxt.arc(0,0,8,0,360,false);
			cxt.closePath();
			cxt.fillStyle="red";
			cxt.fill();
			cxt.stroke();
			cxt.beginPath();
			cxt.arc(0,-150,5,0,360,false);
			cxt.closePath();
			cxt.fillStyle="red";
			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、付费专栏及课程。

余额充值