微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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,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,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,8,false);
			cxt.closePath();
			cxt.fillStyle="red";
			cxt.fill();
			cxt.stroke();
			cxt.beginPath();
			cxt.arc(0,-150,5,false);
			cxt.closePath();
			cxt.fillStyle="red";
			cxt.fill();
			cxt.stroke();
			cxt.restore();
		}
		drawClock();
		setInterval(drawClock,1000);
		</script>
	</body>
</html>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。