canvas画布画表盘

1,012 阅读1分钟

画表盘

1)首先,需要绘制两个圆形作为表盘
2)然后,为表盘添加时间刻度
3) 最后,为表盘添加“指针”(时针,分针,秒针)和圆心,以及文字
4)清空画布,获取系统的时间并封装
5) 然后调用
1、效果图:

2、代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
	#cav{
		display:block;
		margin:0 auto;
		background-color:#f2f2f2;
		}
</style>
</head>
<body>
<canvas width="800" height="800" id="cav"></canvas>
<script type="text/javascript">
1、获取画布
var cav=document.getElementById("cav")
2、获取环境
var ctx=cav.getContext('2d')
			function fun(){
			ctx.clearRect(0,0,800,800)	
			var timeObj=new Date();			获取系统的日期对象
			var hour=timeObj.getHours();			 小时
			var min=timeObj.getMinutes();			 分钟
			var second=timeObj.getSeconds();		 秒数
			console.log("小时:"+hour+"分钟:"+min+"秒数:"+second);
            
			表盘
			ctx.beginPath();
			ctx.strokeStyle="#cfd1ce";
			ctx.lineWidth=5;
			ctx.arc(400,300,200,0,360,false);
			ctx.stroke();
			ctx.closePath();
            
			时刻度
			for(var i=0; i<12; i++){
				ctx.save();
				ctx.translate(400,300);
				ctx.beginPath();
				ctx.rotate(Math.PI/6*i)
				ctx.fillStyle="#000000";
				ctx.fillRect(170,-5,20,10)
				ctx.closePath();
				ctx.restore();
			}
            
			分刻度
			for(var i=0; i<60; i++){
				ctx.save();
				ctx.translate(400,300);
				ctx.beginPath();
				ctx.rotate(Math.PI/30*i)
				ctx.fillStyle="#000000";
				ctx.fillRect(180,-3,10,6)
				ctx.closePath();
				ctx.restore();
			}
            
			秒针
			ctx.save();
			ctx.translate(400,300);
			ctx.rotate(Math.PI/30*second)
			ctx.beginPath();
			ctx.strokeStyle="#575757";
			ctx.lineWidth=4;
			ctx.moveTo(0,15);
			ctx.lineTo(0,-150);
			ctx.stroke();
			ctx.closePath();
			ctx.restore();
            
			分针
			ctx.save();
			ctx.translate(400,300);
			ctx.rotate(Math.PI/30*min)
			ctx.beginPath();
			ctx.strokeStyle="#575757";
			ctx.lineWidth=6;
			ctx.moveTo(0,10);
			ctx.lineTo(0,-110);
			ctx.stroke();
			ctx.closePath();
			ctx.restore();
            
			时针
			ctx.save();
			ctx.translate(400,300);
			ctx.rotate(Math.PI/6*hour)
			ctx.beginPath();
			ctx.strokeStyle="#575757";
			ctx.lineWidth=6;
			ctx.moveTo(0,10);
			ctx.lineTo(0,-60);
			ctx.stroke();
			ctx.closePath();
			ctx.restore();
			
			表盘圆心
			ctx.save();
			ctx.translate(400,300);
			ctx.beginPath();
			ctx.fillStyle="#000000";
			ctx.arc(0,0,8,0,360,false);
			ctx.fill();
			ctx.closePath();
			ctx.restore();
            
			文字
			ctx.beginPath();
			ctx.fillStyle="#333333";
			ctx.font="30px 宋体 blod";
			ctx.fillText("Defend Your Time",280,260);
			ctx.closePath();
			}
            
			fun();
			计时器(函数名称,时间)		每隔多长时间调用一次前面的函数
			setInterval(fun,1000)
</script>
</body>
</html>

3、表盘可以根据获取的时间自己转动。