<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas时钟</title>
</head>
<body>
<canvas id="c" width="300" height="300"></canvas>
<script>
var a_canvas = _$('c'),
w = a_canvas.width,
h = a_canvas.height;
var ctx = a_canvas.getContext('2d');
/*绘制外边框*/
ctx.lineWidth = 1;
ctx.strokeStyle = '#000000';
ctx.strokeRect(0, 0, a_canvas.width, a_canvas.height);
/*把坐标移至矩形中心将大大方便后面角度计算*/
ctx.translate(w/2, h/2);
drawClock(ctx);
function drawClock(context){
/*重置画面*/
context.clearRect(-w/2 + 1, -h/2 + 1, w - 2, h -2);
/*时钟外环*/
var r = (w > h ? h/2 : w/2) - 2;
var len = 0.85 * r;
var px, py;
context.beginPath();
context.arc(0, 0, r, 0, 2*Math.PI);
context.lineWidth = 2;
context.strokeStyle = '0000ff';
context.stroke();
/*绘制时钟数字*/
context.font = '14px Arial';
context.fillStyle = 'black';
context.textAlign = 'center';
context.textBaseline = 'middle';
for(var i = 0; i < 12; i++){
px = len * Math.cos((3 - i) * 2 * Math.PI / 12);
py = -len * Math.sin((3 - i) * 2 * Math.PI / 12);
context.fillText(i === 0 ? 12 : i, px, py);
}
/*绘制时钟指针*/
var date = new Date;
var timeObj = {
hour: date.getHours(),
minute: date.getMinutes(),
seconds: date.getSeconds()
};
/*flag 1,2,3分别代表时针、分针、秒针*/
drawHand(context, timeObj, len, 1);
drawHand(context, timeObj, len, 2);
drawHand(context, timeObj, len, 3);
setTimeout(function(){
drawClock(context);
}, 1000);
}
/*getElementById封装*/
function _$(anchor){
if(typeof anchor !== 'string') return;
return document.getElementById(anchor);
}
/*绘制时钟指针的函数*/
function drawHand(context, timeObj, len, flag){
var config = {};
switch(flag){
case 1:
var hour = timeObj.hour <= 12 ? timeObj.hour : timeObj.hour - 12,
minu = timeObj.minute,
len = len * 0.6,
angle = 2 * Math.PI * (3 - (hour + minu/60)) / 12;
config = {
px: len * Math.cos(angle),
py: -len * Math.sin(angle),
lineWidth: 4
};
break;
case 2:
var minu = timeObj.minute,
sec = timeObj.seconds,
len = len * 0.75,
angle = 2 * Math.PI * (15 - (minu + sec/60)) / 60;
config = {
px: len * Math.cos(angle),
py: -len * Math.sin(angle),
lineWidth: 3
};
break;
case 3:
var sec = timeObj.seconds,
len = len * 0.8,
angle = 2 * Math.PI * (15 - sec) / 60;
config = {
px: len * Math.cos(angle),
py: -len * Math.sin(angle),
lineWidth: 2
};
break;
}
context.beginPath();
context.moveTo(0, 0);
context.lineTo(config.px, config.py);
context.lineWidth = config.lineWidth;
context.strokeStyle = '#000000';
context.stroke();
};
</script>
</body>
</html>