Canvas绘制的简单模拟时钟

本文介绍了一个使用HTML5 Canvas和JavaScript实现的动态时钟绘制方法。通过计算当前时间对应的时针、分针及秒针的角度,并实时更新画布,使得时钟能够准确显示当前时间。

下午碰到这个问题,刚开始懵了,理一下思路,很简单的事情。

 

function getDegree(hour,minute){
    var degree=0;
    var _m=6*minute;
    var _h=30*hour+_m/12;
    degree=_m-_h;
    return degree;
}

顺着这个想法,使用canvas来绘制一个简单的钟表

 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>Clock</title>
	</head>
	<body>
		<canvas id="canvas" width="400" height="400"></canvas>
		<script type="text/javascript" src="line.js"></script>
		<script type="text/javascript">
			window.onload=function(){
				var canvas=document.getElementById("canvas");
				var context=canvas.getContext("2d");

				var secondHand=new Line(50,1,'#ff0000');
				var minuteHand=new Line(40,2,'#000000');
				var hourHand=new Line(25,3,'#000000');

				secondHand.x=minuteHand.x=hourHand.x=canvas.width/2;
				secondHand.y=minuteHand.y=hourHand.y=canvas.height/2;

				var count=0;

				(function animationLoop(){
					window.requestAnimationFrame(animationLoop,canvas);
					

					if(count===60){
						count=0;
						var now=new Date();
						var second=now.getSeconds();
						secondHand.rotation=(second*6-90)*Math.PI/180;
						var minute=now.getMinutes();
						minuteHand.rotation=(minute*6-90)*Math.PI/180+secondHand.rotation/60;
						var hour=now.getHours()%12;
						hourHand.rotation=(hour*30-90)*Math.PI/180+minuteHand.rotation/12;

						context.clearRect(0,0,canvas.width,canvas.height);
						context.beginPath();
						context.arc(canvas.width/2,canvas.height/2,60,0,Math.PI*2,true);
						context.closePath();
						context.stroke();
						secondHand.paint(context);
						minuteHand.paint(context);
						hourHand.paint(context);
					}else{
						count++;
					}
				})();
			};
		</script>
	</body>
</html>
 

下面是画线的函数

function Line(width,height,color){
	this.x=0;
	this.y=0;
	this.width=width||100;
	this.height=height||1;
	this.color=color||'#ff0000';
	this.rotation=0;
}

Line.prototype.paint=function(context){
	context.save();
	context.translate(this.x,this.y);
	context.rotate(this.rotation);
	context.strokeStyle=this.color;
	context.lineWidth=this.height;
	context.beginPath();
	context.moveTo(0,0);
	context.lineTo(this.width,0);
	context.closePath();
	context.stroke();
	context.restore();	
};
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值