<!DOCYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<canvas id="canvas" width="500px" height="500px"></canvas>
<script type="text/javascript">
//获取canvas对象
var oCanvas = document.getElementById("canvas");
//获取上下文(画笔)默认画笔颜色为黑色 fillStyle改变颜色
var context = oCanvas.getContext("2d");
(function drawClock () {
//清空画布
context.clearRect(0,0,oCanvas.width,oCanvas.height);
//绘制背景
context.fillStyle="#eee";//实心
//绘制矩形
context.fillRect(0, 0, oCanvas.width,oCanvas.height);
//空心
//context.strokeStyle = "#eee";
//绘制矩形
//context.strokeRect(0, 0, oCanvas.width,oCanvas.height);
//绘制表盘
context.beginPath();//开始
context.arc(250, 250, 200, 0, 2 * Math.PI);
context.strokeStyle="#000";
context.lineWidth = 4;//设置线的宽度
context.stroke();//开始画圆
context.closePath();//关闭
//绘制分刻度
context.save();//保存当前状态
context.translate(250,250);//改变坐标轴原点
for(var i=0; i<60; i++){
context.beginPath();
context.rotate(Math.PI/30);//旋转
context.moveTo(0,-185);//起点
context.lineTo(0,-195);//终点
context.lineWidth = 2;
context.stroke();
context.closePath();
}
context.restore();//将画布恢复到初始状态
//绘制时刻度
context.save();
context.translate(250,250);//改变坐标轴原点
for(var i=0; i<12; i++){
context.beginPath();
context.rotate(Math.PI/6);//旋转
context.moveTo(0,-175);
context.lineTo(0,-195);
context.lineWidth = 4;
context.stroke();
context.closePath();
}
context.restore();//将画布恢复到初始状态
//绘制指针
//获取当前时间
var now = new Date();
var sec = now.getSeconds();
var min = now.getMinutes() + sec / 60;
var hour = now.getHours() + min / 60;
//绘制时针指针
context.save();
context.translate(250,250);
context.rotate(Math.PI / 6*hour);
context.beginPath();
context.moveTo(0,10);
context.lineTo(0,-150);
context.lineWidth = 4;
context.stroke();
context.closePath();
context.restore();
//繪製分針指針
context.save();
context.translate(250,250);
context.rotate(Math.PI / 30*min);
context.beginPath();
context.moveTo(0,15);
context.lineTo(0,-165);
context.lineWidth = 3;
context.stroke();
context.closePath();
context.restore();
//绘制秒针指针
context.save();
context.translate(250,250);
context.rotate(Math.PI / 30 * sec);
context.beginPath();
context.moveTo(0,25);
context.lineTo(0,-160);
context.lineWidth = 2;
context.strokeStyle="red";
context.stroke();
context.closePath();
//画秒针上的两个小圆
context.beginPath();
context.arc(0,0,5,0,2*Math.PI);
context.fillStyle="white";
context.strokeStyle="red";
context.fill();
context.stroke();
context.closePath();
context.beginPath();
context.arc(0,-130,5,0,2*Math.PI);
context.fillStyle="white";
context.strokeStyle="red";
context.fill();
context.stroke();
context.closePath();
context.restore();
window.requestAnimationFrame(drawClock);
})();
</script>
</body>
</html>