一个精美的时钟动画

完整代码,代码有注释就不说明了

<!DOCTYPE html>
<html>
	<head lang="en">
		<meta charset="GBK">
		<title></title>
		<style>
* {
	margin: 0;
	padding: 0;
}

canvas {
	border: 1px solid;
	position: absolute;
	margin-left: 200px;
}
</style>
	</head>
	<body>
		<canvas id='canvas'></canvas>
	</body>

	<script type="text/javascript">
	var canvas = document.getElementById('canvas');
		canvas.width='300';
		canvas.height='300';
	var ctx = canvas.getContext("2d");	
	
	function clock(){
		  ctx.save();
		  ctx.clearRect(0,0,300,300);//清理画布
		  ctx.translate(150,150);//
		  ctx.scale(0.7,0.7);//缩放比例
		  ctx.rotate(-Math.PI/2);//负向旋转2分之1个π 
		  ctx.strokeStyle = "black";
		  ctx.fillStyle = "white";
		  ctx.lineWidth = 8;
		  ctx.lineCap = "round";
		  
		  //画小时的格子
		  ctx.save();
		  //边旋转边画
		  for(var i=0;i<12;i++){
		  	ctx.beginPath();
		  	ctx.rotate(30*2*Math.PI/360);//等于Math.PI/6   总共360度分成12份,每份30度,转换成π
		  	ctx.moveTo(100,0);
		  	ctx.lineTo(120,0);
		  	ctx.stroke();
		  	ctx.closePath();
		  }
		  ctx.restore();
		  
		  //画分钟的格子
		  ctx.save();
		  //边旋转边画
		  ctx.lineWidth = 5;//细一些
		  for(var i=0;i<60;i++){
		  	if(i%5!=0){//小时的格子占据不用再次画
		  		ctx.beginPath();
			  	ctx.moveTo(115,0);
			  	ctx.lineTo(120,0);
			  	ctx.stroke();
			  	ctx.closePath();
		  	}
		  	ctx.rotate(6*2*Math.PI/360);//旋转 等于Math.PI/30   总共360度分成60份,每份6度,转换成π
		  }
		  ctx.restore();
		
		  //计算时分秒
		  var now = new Date();
		  var sec = now.getSeconds();
		  var min = now.getMinutes();
		  var hour  = now.getHours();
		  hour = hour>=12 ? hour-12 : hour;
		
		  //画时针
		  ctx.fillStyle = "black";
		  ctx.save();
		  ctx.beginPath();
		  ctx.lineWidth = 14;
		  //旋转角度 小时:hour * (Math.PI/6)  分钟的话,在小时的基础上再多除以60,秒钟则在分钟的基础上再除以60,3者加起来
		  ctx.rotate(hour * (Math.PI/6) + min * (Math.PI/(6*60)) + sec * (Math.PI/(6*60*60)) );
		  ctx.moveTo(-20,0);
		  ctx.lineTo(80,0);
		  ctx.stroke();
		  ctx.restore();
		  
		  //画分针
		  ctx.save();
		  ctx.beginPath();
		  ctx.lineWidth = 10;
		  //旋转角度
		  ctx.rotate(min * (Math.PI/30)+ sec * (Math.PI/(30*60)) );
		  ctx.moveTo(-28,0);
		  ctx.lineTo(110,0);
		  ctx.stroke();
		  ctx.restore();
		  	
		  //画秒针
		  ctx.save();
		  ctx.beginPath();
		  ctx.strokeStyle = "red";
		  ctx.lineWidth = 6;
		  //旋转角度
		  ctx.rotate(sec * (Math.PI/30));
		  ctx.moveTo(-36,0);
		  ctx.lineTo(126,0);
		  ctx.stroke();
		  //中心画一个红色小圆
		  ctx.arc(0,0,6,0,2*Math.PI);
		  ctx.stroke();
		  ctx.restore();
		  
		  //钟外围的大圆	
		  ctx.save();
		  ctx.lineWidth = 14;
		  ctx.beginPath();
		  ctx.strokeStyle='lightblue';
		  ctx.arc(0,0,142,0,2*Math.PI);
		  ctx.stroke();
		  ctx.restore();
		  
		  ctx.restore();
		  //执行动画
		  window.requestAnimationFrame(clock);
	}
	//执行动画	
 	window.requestAnimationFrame(clock);
		
	
</script>
</html>

猜你喜欢

转载自blog.csdn.net/dkm123456/article/details/112789321