下午碰到这个问题,刚开始懵了,理一下思路,很简单的事情。
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();
};
本文介绍了一个使用HTML5 Canvas和JavaScript实现的动态时钟绘制方法。通过计算当前时间对应的时针、分针及秒针的角度,并实时更新画布,使得时钟能够准确显示当前时间。
2408

被折叠的 条评论
为什么被折叠?



