HTML5+Canvas实现一款圆形时钟动画特效

HTML5 herman 331浏览 0评论

很多博客都一个圆形时钟摆件,看起来很炫。今天我借助HTML5和Canvas为大家实现一款会动的圆形时钟。

在学习本文之前,你需要对HTML5和Canvas有一定的基础知识。本案例的代码非常精简,总代码100行左右。下面我们先看看该时钟动画的运行效果。

HTML5 Canvas 圆形时钟

下面是该案例的实现源码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML5 Canvas 圆形时钟动画|业余草:www.xttblog.com</title>
<style type="text/css">
	#myCanvas{
		display: block;
		margin:10px auto;
	}
</style>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script type="text/javascript">
	var myCanvas = document.getElementById('myCanvas');
	var c = myCanvas.getContext('2d');
	function clock(){
		c.clearRect(0,0,400,400);
		var data = new Date();
		var sec =data.getSeconds();
		var min =data.getMinutes();
		var hour=data.getHours();
		//业余草:www.xttblog.com
		c.save();
		c.translate(200,200);
		c.rotate(-Math.PI/2);
		//业余草:www.xttblog.com
		//分钟刻度线
		for(var i=0;i<60;i++){	//画12个刻度线			
			c.beginPath();
			c.strokeStyle = "#f00";				
			c.lineWidth = 5 ;
			c.moveTo(117,0);
			c.lineTo(120,0);
			c.stroke();
			c.rotate(Math.PI/30); //每个6deg画一个时钟刻度线
			c.closePath();
		}
		//业余草:www.xttblog.com
		//时钟刻度线
		for(var i=0;i<12;i++){	//画12个刻度线			
			c.beginPath();
			c.strokeStyle = "#000";				
			c.lineWidth = 8 ;
			c.moveTo(100,0);
			c.lineTo(120,0);
			c.stroke();
			c.rotate(Math.PI/6); //每个30deg画一个时钟刻度线
			c.closePath();
		}
		//外表盘
		c.beginPath();
		c.strokeStyle = "pink";
		c.arc(0,0,145,0,Math.PI*2);
		c.lineWidth = 12 ;
		c.stroke();
		c.closePath();
		//业余草:www.xttblog.com
		//画时针
		hour = hour>12?hour-12:hour;
		//console.log(hour);
		c.beginPath();
		c.save();
		c.rotate(Math.PI/6*hour+Math.PI/6*min/60+Math.PI/6*sec/3600);
		c.strokeStyle = "yellowgreen";
		c.lineWidth = 4 ;
		c.moveTo(-20,0);
		c.lineTo(50,0);
		c.stroke();
		c.restore();
		c.closePath();
		//业余草:www.xttblog.com
		//画分针
		//console.log(min);
		c.beginPath();
		c.save();
		c.rotate(Math.PI/30*min+Math.PI/30*sec/60);
		c.strokeStyle = "springgreen";
		c.lineWidth = 3 ;
		c.moveTo(-30,0);
		c.lineTo(70,0);
		c.stroke();
		c.restore();
		c.closePath();
		//画秒针
		c.beginPath();
		c.save();
		c.rotate(Math.PI/30*sec);
		c.strokeStyle = "red";
		c.lineWidth = 2 ;
		c.moveTo(-40,0);
		c.lineTo(120,0);
		c.stroke();
		c.restore();
		c.closePath();
		c.restore();
	}
	clock();
	setInterval(clock,1000);
</script>
</body>
</html>

喜欢的朋友可以自行的将源码保存到文件中运行看看效果。

业余草公众号

最后,欢迎关注我的个人微信公众号:业余草(yyucao)!

本文原文出处:业余草: » HTML5+Canvas实现一款圆形时钟动画特效