您的位置:首页 > 其它

Canvas绘制的简单模拟时钟

2012-01-17 17:09 357 查看

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

 

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();
};
 

 

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: