用canvas绘制时钟

canvas是h5新增的元素,下面我们开学习一下怎样用canvas绘制一个时钟

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	<style>
			
			canvas{
				border:1px solid #000000;
			}
		</style>
	</head>
	<body>
		<canvas id="can" width="500" height="500"></canvas>
	</body>
	<script type="text/javascript">
		var can=document.getElementById('can');
		var ctx=can.getContext('2d');
		
	
		function shijian(){
	    ctx.clearRect(0,0,500,500);
		
		//表盘
		ctx.save();
		ctx.beginPath();
		ctx.lineWidth=5;
		ctx.arc(250,250,100,0,Math.PI*2);
		ctx.stroke();
		ctx.closePath();
		ctx.restore();
	
		
		//刻度
        for(var i=0;i<60;i++){
        ctx.save();
		ctx.translate(250,250);
		ctx.rotate(i*Math.PI/30);
		ctx.beginPath();
		if(i%5==0){
			ctx.moveTo(0,-100);
		    ctx.lineTo(0,-85); 	
		    ctx.lineWidth =5;
		}
		else{
			ctx.moveTo(0,-100);
		    ctx.lineTo(0,-90); 	
		    ctx.lineWidth =2;
		}
		ctx.closePath();
		ctx.stroke();
		ctx.restore();
      }
		//获取时间
	
		var time=new Date();
		var hours=time.getHours();
		var min=time.getMinutes();
		var sec=time.getSeconds();
		var hour=hours-12>0?hours-12:hours;
	
		
		//时针
		
		ctx.save();
		ctx.translate(250,250);
		ctx.rotate((hour+min/60)*Math.PI/6);
		ctx.beginPath();
		ctx.moveTo(0,0);
		ctx.lineTo(0,-50); 	
		ctx.lineWidth=6;
		ctx.stroke();
		ctx.closePath();
		ctx.restore();
		//分针
		ctx.save();
		ctx.translate(250,250);
		ctx.rotate((min+sec/60)*Math.PI/60);
		ctx.beginPath();
		ctx.moveTo(0,0);
		ctx.lineTo(0,-70); 	
		ctx.lineWidth=4;
		ctx.stroke();
		ctx.closePath();
		ctx.restore();
		//秒针
		ctx.save();
		ctx.translate(250,250);
		ctx.rotate(sec*Math.PI/30);
		ctx.beginPath();
		ctx.moveTo(0,0);
		ctx.lineTo(0,-80); 	
		ctx.lineWidth=2;
		ctx.stroke();
		ctx.closePath();
		ctx.restore();
		//圆心
		ctx.save();
		ctx.translate(250,250);
		ctx.beginPath();
		ctx.arc(0,0,5,0,Math.PI*2);
		ctx.fillStyle='blue';
		ctx.fill();
		ctx.closePath();
		ctx.restore();
		//字体
	    ctx.save();
		ctx.translate(250,250);
	    ctx.font="20px Arial";
		ctx.textAlign='center';
		ctx.fillText("天明城",0,-60);
        ctx.restore();
		
}
shijian();
setInterval(shijian,1000);
</script>
</html>

效果如下

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Honey_tianming/article/details/82829367