H5 canvas小案例-钟表

效果图:
在这里插入图片描述
直接上代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>钟表</title>
		<style type="text/css">
			body{
				width: 100vw;
				height: 100vh;
				overflow: hidden;
				display: flex;
				justify-content: center;
				align-items: center;
			}
			#timer{
				background-color: black;
			}
		</style>
	</head>
	<body>
		<div id="timerbox">
			<canvas id="timer" width="300" height="300"></canvas>
		</div>
		<script type="text/javascript">
			const timer = document.querySelector("#timer");
			const ct = timer.getContext("2d");
			// 转换原点
			ct.translate(150,150);
			function drawTimer(){
				// 清除上一针
				ct.clearRect(-150,-150,300,300)
				// 画圆
				ct.beginPath();
				ct.strokeStyle = 'firebrick';
				ct.lineWidth = "10";
				ct.arc(0,0,120,0,360,false);
				ct.stroke();
				ct.restore()
				// 画小刻度
				ct.lineWidth = "3";
				ct.strokeStyle = "lightgreen";
				for (var j = 0; j < 60; j++) {
					ct.save()
					ct.beginPath();
					ct.rotate(j*6*Math.PI/180);
					ct.moveTo(0,-113);
					ct.lineTo(0,-103);
					ct.stroke();
					ct.restore()
				}
				// 画大刻度
				ct.lineWidth = "5";
				ct.strokeStyle = "hotpink";
				for (var i = 0; i < 12; i++) {
					ct.save()
					ct.beginPath();
					ct.rotate(i*30*Math.PI/180);
					ct.moveTo(0,-113);
					ct.lineTo(0,-93);
					ct.stroke();
					ct.restore()
				}
				const now = new Date();
				let m = now.getMinutes();
				let s = now.getSeconds();
				let H = now.getHours() + m / 60;
				H = H > 12 ? H - 12 : H;
				H = H + m / 60;
				m = m + s / 60;
				// 画时针
				ct.lineWidth = "8";
				ct.strokeStyle = "lightseagreen";
				ct.save()
				ct.beginPath();
				ct.rotate(H/12*360*Math.PI/180);
				ct.moveTo(0,10);
				ct.lineTo(0,-60);
				ct.lineCap = "round"
				ct.closePath()
				ct.stroke();
				ct.restore()
				// 画分针
				ct.lineWidth = "5";
				ct.strokeStyle = "lightsalmon";
				ct.save()
				ct.beginPath();
				ct.rotate(m/60*360*Math.PI/180);
				ct.moveTo(0,20);
				ct.lineTo(0,-75);
				ct.lineCap = "round"
				ct.closePath()
				ct.stroke();
				ct.restore()
				// 画秒针
				ct.lineWidth = "2";
				ct.strokeStyle = "lightskyblue";
				ct.fillStyle = "lightgreen";
				ct.save()
				ct.beginPath();
				ct.rotate(s/ 60 *360*Math.PI/180);
				ct.arc(0,-70,4,0,360,false);
				ct.fill()
				ct.moveTo(0,30);
				ct.lineTo(0,-90);
				ct.lineCap = "round"
				ct.closePath()
				ct.stroke();
				ct.restore()
				ct.fillStyle = "blue";
				ct.beginPath();
				ct.arc(0,0,5,0,360,false);
				ct.fill();
			}
			drawTimer();
			setInterval(drawTimer,1000);			
		</script>
	</body>
</html>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值