//半径
var r = 130;
//重置原点
ctx.save();
ctx.translate(400, 500); //使用translate重置原点
function drawClock() { //画时钟不动的背景
//时钟外圈
ctx.beginPath();
ctx.arc(0, 0, r, 0, 2*Math.PI);
ctx.strokeStyle = 'blue';
ctx.lineWidth = 5;
ctx.stroke();
ctx.closePath();
//圆心
ctx.beginPath();
ctx.arc(0,0,5,0, 2*Math.PI);
ctx.fillStyle = 'black';
ctx.lineWidth = 1;
ctx.fill();
ctx.closePath();
//画hour数字
var hour = [1,2,3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
hour.forEach(function (value) {
var xValue = (r-28)*Math.cos(Math.PI*(value-3)/6);
var yValue = (r-28)*Math.sin(Math.PI*(value-3)/6);
ctx.font = "18px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = 'black';
ctx.fillText(value, xValue, yValue);
});
//画刻度
for (var i=0; i<60; i++) {
ctx.beginPath();
var x = (r - 15)*Math.cos(i*2*Math.PI/60);
var y = (r - 15)*Math.sin(i*2*Math.PI/60);
if (i%5 === 0) {
ctx.strokeStyle = "#000";
ctx.arc(x, y, 2, 0, 2*Math.PI, true);
} else {
ctx.strokeStyle = "#bbb";
ctx.arc(x, y, 2, 0, 2*Math.PI, true);
}
ctx.stroke();
ctx.closePath();
}
}
function moveClock() { //画会动的指针
let now = new Date();
let h = now.getHours();
ctx.save();
ctx.beginPath();
ctx.rotate(h*Math.PI/6);
ctx.moveTo(0,10);
ctx.lineTo(0, 55-r);
ctx.strokeStyle = 'blue';
ctx.lineWidth = 8;
ctx.lineCap = 'round';
ctx.stroke();
ctx.closePath();
ctx.restore();
//分针
var min = now.getMinutes();
ctx.save();
ctx.beginPath();
ctx.rotate(min*Math.PI/30);
ctx.moveTo(0,10);
ctx.lineTo(0, 40-r);
ctx.strokeStyle = 'green';
ctx.lineWidth = 8;
ctx.lineCap = 'round';
ctx.stroke();
ctx.closePath();
ctx.restore();
//s针
var s = now.getSeconds();
ctx.save();
ctx.beginPath();
ctx.rotate(s*Math.PI/30);
ctx.moveTo(0,10);
ctx.lineTo(0, 30-r);
ctx.strokeStyle = 'red';
ctx.lineWidth = 3;
ctx.lineCap = 'round';
ctx.stroke();
ctx.closePath();
ctx.restore();
}
setInterval(function () { //隔一秒调用一次上面两个方法,调用之前先清除画板,否则会有很多指针。
ctx.clearRect(-130,-130, 260, 260);
drawClock();
moveClock();
}, 1000);