<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
window.onload=function(){
function clock(){
//1.获取画布
var canvas=document.getElementById('canvas');
//2.获取画笔
var cx=canvas.getContext('2d');
//3.设置画笔样式
cx.fillStyle='green';
cx.strokeStyle='black';
//4.绘制图形
//绘制表盘
cx.beginPath();
cx.arc(250,250,200,0,Math.PI*2);
cx.closePath();
cx.fill();
//绘制时刻度
cx.lineWidth=2;
for(var i=0;i<12;i++){
cx.save();
cx.translate(250,250);
cx.rotate(i*Math.PI/6);//先旋转再绘制
cx.beginPath()
cx.moveTo(0,-180);
cx.lineTo(0,-200);
cx.closePath();
cx.stroke();
cx.restore();
cx.fillStyle='black';
cx.font='16px bold';
cx.save();
cx.translate(250,250);
cx.rotate(i*Math.PI/6);
cx.rotate(Math.PI/6);
cx.fillText(i+1,-5,-220);
cx.restore();
}
//绘制分刻度
for(var i=0;i<60;i++){
cx.save();
cx.translate(250,250);
cx.rotate(i*Math.PI/30);//先旋转再绘制
cx.beginPath()
cx.moveTo(0,-190);
cx.lineTo(0,-200);
cx.closePath();
cx.stroke();
cx.restore();
}
//绘制时针
var today=new Date();
var hour=today.getHours();
var min=today.getMinutes();
var sec=today.getSeconds();
hour=hour+min/60;//eg:3.5小时
cx.lineWidth=5;
cx.save();
cx.strokeStyle='black';
cx.translate(250,250);
cx.rotate(hour*Math.PI/6)
cx.beginPath()
cx.moveTo(0,-130);
cx.lineTo(0,8);
cx.closePath();
cx.stroke();
cx.restore();
//绘制分针
cx.lineWidth=3;
cx.save();
cx.strokeStyle='black';
cx.translate(250,250);
cx.rotate(min*(Math.PI/30))
cx.beginPath()
cx.moveTo(0,-150);
cx.lineTo(0,8);
cx.closePath();
cx.stroke();
cx.restore();
//绘制秒针
cx.lineWidth=1;
cx.save();
cx.strokeStyle='red';
cx.translate(250,250);
cx.rotate(sec*(Math.PI/30))
cx.beginPath()
cx.moveTo(0,-170);
cx.lineTo(0,8);
cx.closePath();
cx.stroke();
cx.restore();
//绘制交界处
cx.fillStyle='white';
cx.save();
cx.translate(250,250);
cx.beginPath();
cx.arc(0,0,5,0,Math.PI*2)
cx.closePath();
cx.fill();
cx.lineWidth=2;
cx.strokeStyle='red';
cx.stroke();
cx.restore();
setTimeout(clock,1000);
}
clock()
}
</script>
</head>
<body>
<canvas id="canvas" width="600px" height="600px" style="background-color: #ccc;"></canvas>
</body>
</html>
效果图如下: