<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>clock</title>
</head>
<body>
<div >
<canvas width=800 height=400 id="clock"></canvas>
</div>
<script>
var sAngle, mAngle,hAngle;
var clock=document.getElementById('clock');
var context=clock.getContext('2d');
//初始时间
function newdata(){
var nd=new Date();
var hour=nd.getHours();
var minute=nd.getMinutes();
var second=nd.getSeconds();
sAngle=Math.PI*2*(second%60)/60;
mAngle=Math.PI*2*(minute%60)/60+sAngle/60;
hAngle=Math.PI*2*(hour%12)/12+mAngle/12;
}
//圆周
function rounds(){
context.save();
context.beginPath();
context.arc(clock.width/2,clock.height/2,150,0,Math.PI*2,true);
context.closePath();
context.strokeStyle='#bbb'
context.lineWidth=6;
context.stroke();
context.restore();
}
//数字
function number(){
var num=[];
for(var i=1; i<13; i++){
num[i-1]=i+3;
if((i+3)>12){
num[i-1]=3-(12-i);
}
}
var ar=Math.PI/6;
context.save();
context.fillStyle='#777';
context.font="19px 微软雅黑";
context.textBaseline="middle";
context.textAlign="center";
context.translate(clock.width/2,clock.height/2);
for(var i=0; i<num.length; i++){
context.fillText(num[i],135*Math.cos(ar*(i+1)),135*Math.sin(ar*(i+1)));
}
context.restore();
}
//针
function needle(h,m,s){
context.save();
context.translate(clock.width/2,clock.height/2);
line(s,110,'#aaa',3) //秒针
line(m,120,'#999',4) //分针
line(h,70,'#888',4) //时针
context.restore();
}
function line(s,len,col,lw){
context.save();
context.beginPath();
context.rotate(s);
context.moveTo(0,15);
context.lineTo(0,-len);
context.strokeStyle=col;
context.lineWidth=lw;
context.stroke();
context.restore();
}
newdata();
rounds();
number();
needle(hAngle,mAngle,sAngle);
setInterval(function(){
context.clearRect(0,0,clock.width,clock.height);
newdata();
rounds();
number();
needle(hAngle,mAngle,sAngle);
},1000)
</script>
</body>
</html>
热门评论
重新写了,做了些拓展:http://voicefu.oschina.io/clock
码云地址:https://git.oschina.net/voicefu/clock
github :https://github.com/18219304774/clock/tree/new/clock