<html>
<head>
<title>时钟</title>
</head>
<style>
#canvas{
background: #1977ca
}
</style>
<body>
<canvas id="canvas" width="500" height="300">
</canvas>
<script>
var canvas=document.getElementById("canvas"),
context=canvas.getContext('2d'),
font_height=15,
margin=35,
hand_truncation=canvas.width/150,
hour_hand_truncation=canvas.width/20,
numeral_spacing=30,
raduis=canvas.height/2-margin,
hand_radius=raduis+numeral_spacing;
// console.log("半径:"+raduis);
//画表格
function table(){
xLen=500;
yLen=300;
context.lineWidth = 0.5;
context.save();
context.beginPath();
for(var i=0;i<xLen;i++){
context.fillText(i*20,i*20+1,10);
context.moveTo(1,i*20+1);
context.lineTo(xLen,i*20+1);
}
for(var i=0;i<yLen;i++){
context.fillText(i*20,0,i*20+1);
context.moveTo(i*20+1,1);
context.lineTo(i*20+1,yLen);
}
context.strokeStyle="#FFFFFF";
context.stroke();
}
//画圆
function drawCircle(){
context.restore();
context.lineWidth = 4;
context.beginPath();
//起始角,以弧度计(弧的圆形的三点钟位置是 0 度)。
context.arc(canvas.width/2,canvas.height/2,raduis,0,Math.PI*2);
context.stroke();
}
//画心
function drawCenter(){
context.beginPath();
context.arc(canvas.width/2,canvas.height/2,5,0,Math.PI*2);
context.fill();
}
function darwHand(loc,isHour){
//角度 计算 比如当前为60分钟 360 * (60/60); 就回到原点 原点就是3点钟开始画 x 轴 但现实时12点中为起点 就需要减去(Math.PI/2)90度
var angle=(Math.PI*2)*(loc/60)-(Math.PI/2),
//让时针分钟长度不同
handRadius=isHour?raduis-hand_truncation-hour_hand_truncation:raduis-hand_truncation;
// console.log("角度:"+angle);
context.moveTo(canvas.width/2,canvas.height/2);
// handRadius=115;
//Math.sin(angle)*handRadius 余玄 乘以半径(斜边) 等于在x轴的长度 在加上 canvas.width/2 就等于当前指针在x的刻度
var x=canvas.width/2+Math.cos(angle)*handRadius;
//Math.sin(angle)*handRadius 正玄 乘以半径(斜边) 等于在y轴的长度 在加上 canvas.height/2 就等于当前指针在y的刻度
var y=canvas.height/2+Math.sin(angle)*handRadius;
// console.log("x:"+x);
// console.log("y:"+y);
context.lineTo(x,y);
context.stroke();
}
//时间指针
function drwaHands(){
var date=new Date,
hour=date.getHours();
hour=hour>12?hour-12:hour;
//(hour*5) :一共十二小时 分成5份 (date.getMinutes()/60)
timeHour=(hour*5)+(date.getMinutes()/60)*5;
// console.log("分钟:"+date.getMinutes()/60)*5
darwHand(timeHour,true)
darwHand(date.getMinutes(),false)
darwHand(date.getSeconds(),false)
}
//画刻度
function deawNumerals(){
context.save();
var numbrals=[1,2,3,4,5,6,7,8,9,10,11,12],
angle=0,
numbralwidth=0;
numbrals.forEach(function(num){
//获取字符宽度
numbralwidth=context.measureText(num).width;
console.log("时间:"+numbralwidth);
//获取角度
angle=(Math.PI*2)*((num*5)/60)-Math.PI/2;
context.font="20px Arial";
context.fillStyle ="#FFFFFF";
var x=canvas.width/2+(Math.cos(angle)*raduis)-numbralwidth/2;
var y=canvas.height/2+(Math.sin(angle)*raduis+6.5);
context.fillText(num,x, y);
});
context.restore();
}
loop=setInterval(()=>{
// clearRect() 方法清空给定矩形内的指定像素。
context.clearRect(0,0,canvas.width,canvas.height)
table();
drawCircle();
drawCenter();
drwaHands();
deawNumerals();
},100);
</script>
</body>
</html>