canvas时钟

 

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>

	<body>
		<canvas id="canvas" width="1000" height="600"></canvas>
		<script type="text/javascript">
			let canvas = document.getElementById('canvas')
			let ctx = canvas.getContext('2d')
			
			class Clock{
				constructor(s,m,h){
					this.ox = 500,
					this.oy = 300,
					this.r = 100,
					this.r2 = 90,
					this.s =  s; //秒
					this.m =  m; //分
					this.h =  h; //时
				}
				
				draw(){
					ctx.beginPath()
					ctx.arc(this.ox, this.oy, this.r, 0, Math.PI * 2, true)
					
					for(let i = 0; i < 60; i++) {
						ctx.moveTo(this.ox, this.oy)
						let x = Math.sin(i * Math.PI / 30) * this.r + this.ox
						let y = Math.cos(i * Math.PI / 30) * this.r + this.oy
	
						ctx.lineTo(x, y)
						ctx.stroke();
					}
	
					ctx.beginPath();
					ctx.fillStyle = '#fff';
					ctx.arc(this.ox, this.oy, this.r2, 0, Math.PI * 2, true)
					ctx.fill();
	
					ctx.beginPath();
					for(let i = 0; i < 12; i++) {
						ctx.moveTo(this.ox, this.oy)
						let x = Math.sin(i * Math.PI / 180 * 30) * this.r2 + this.ox
						let y = Math.cos(i * Math.PI / 180 * 30) * this.r2 + this.oy
	
						ctx.lineTo(x, y)
						ctx.stroke();
					}
					
					ctx.beginPath();
					ctx.fillStyle = '#fff';
					ctx.arc(this.ox, this.oy, this.r2-10, 0, Math.PI * 2, true)
					ctx.fill();
					
					this.setDate()
					
				}
				setDate(){
					// 时
					ctx.beginPath();
					ctx.moveTo(this.ox, this.oy)
					ctx.lineWidth = 3
					ctx.strokeStyle = "black"
					
					let hx = -Math.cos(-this.h * Math.PI / 30) * (this.r-30) + this.ox
					let hy = -Math.sin(-this.h * Math.PI / 30) * (this.r-30) + this.oy
					
					ctx.lineTo(hx, hy)
					ctx.stroke();
					// 分
					ctx.beginPath();
					ctx.moveTo(this.ox, this.oy)
					ctx.lineWidth = 2
					ctx.strokeStyle = "blue"
					
					let mx = -Math.sin(-this.m * Math.PI / 30) * (this.r-20) + this.ox
					let my = -Math.cos(-this.m * Math.PI / 30) * (this.r-20) + this.oy
					
					ctx.lineTo(mx, my)
					ctx.stroke();
					
					// 秒
					ctx.beginPath();
					ctx.moveTo(this.ox, this.oy)
					ctx.strokeStyle = "red"
					
					let sx = -Math.sin(-this.s * Math.PI / 30) * (this.r-10) + this.ox
					let sy = -Math.cos(-this.s * Math.PI / 30) * (this.r-10) + this.oy
					
					ctx.lineTo(sx, sy)
					ctx.stroke();
					
					ctx.strokeStyle = "black"
					ctx.lineWidth = 1
				}
				
			}
			
			
			
			setInterval(function(){
				let clock = new Clock(new Date().getSeconds(),new Date().getMinutes(),new Date().getHours())
				ctx.clearRect(0, 0, 1000, 600)
				clock.draw()
			},1000)
		</script>
	</body>

</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值