<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>my clock</title>
</head>
<body>
<!--画布-->
<canvas id="canvas"
width="500"
height="500">
您的浏览器已过时,请升级
</canvas>
<script>
var canvas=document.getElementById('canvas');
var cxt=canvas.getContext('2d');
// 表盘
function drawClock()
{
cxt.clearRect(0,0,500,500);
// 清屏
var now =new Date();
var hour=now.getHours();
var min =now.getMinutes();
var sec =now.getSeconds();
hour=hour+min/60;
hour=hour>12?hour-12:hour;
cxt.lineWidth=10;
// 画笔宽度为10
cxt.strokeStyle="black";
// 颜色
cxt.beginPath();
cxt.arc(250,250,200,0,360,false);
// x轴,y轴,半径,,角度,顺时针/逆时针
cxt.closePath()
cxt.stroke();
// 方法
for(var i=0;i<12;i++)
{
cxt.save();
cxt.lineWidth=7;
cxt.strokeStyle="black";
cxt.translate(250,250);
cxt.rotate(i*30*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,170);
cxt.lineTo(0,190)
cxt.closePath();
cxt.stroke();
cxt.restore();
// 恢复/还原
}
for(var i=0;i<60;i++)
{
cxt.save();
cxt.lineWidth=5;
cxt.strokeStyle="black";
cxt.translate(250,250);
cxt.rotate(i*6*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,180);
cxt.lineTo(0,190)
cxt.closePath();
cxt.stroke();
cxt.restore();
// 恢复/还原
}
// 时针
cxt.save();
cxt.lineWidth=7;
cxt.strokeStyle="black";
cxt.translate(250,250);
cxt.rotate(hour*30*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-140);
cxt.lineTo(0,10)
cxt.closePath();
cxt.stroke();
cxt.restore();
// 分针
cxt.save();
cxt.lineWidth=7;
cxt.strokeStyle="black";
cxt.translate(250,250);
cxt.rotate(min*30*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-160);
cxt.lineTo(0,10)
cxt.closePath();
cxt.stroke();
cxt.restore();
// 秒针
cxt.save();
cxt.lineWidth=3;
cxt.strokeStyle="red";
cxt.translate(250,250);
cxt.rotate(sec*6*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-170);
cxt.lineTo(0,10)
cxt.closePath();
cxt.stroke();
cxt.beginPath();
cxt.arc(0,0,5,0,360,false);
cxt.closePath();
cxt.fillStyle="gray";
cxt.fill();
cxt.stroke();
cxt.beginPath();
cxt.arc(0,-150,5,0,360,false);
cxt.closePath();
cxt.fillStyle="gray";
cxt.fill();
cxt.stroke();
cxt.restore();
}
drawClock();
// 调用函数
setInterval(drawClock,1000);
</script>
</body>
</html>