原理代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
canvas{
margin: 20px 400px ;
}
</style>
</head>
<body>
<canvas width="500px" height="500px"></canvas> <script>
var can=document.getElementsByTagName("canvas")[];
var x=can.getContext("2d"); function clock(){ //每次执行代码清楚一次画布
x.clearRect(,,,) //创建一个实心圆
x.beginPath();
x.fillStyle="blue";
x.arc(,,,Math.PI*/,Math.PI*/)
x.fill()
x.closePath(); //再来一个白色的小圆
x.beginPath();
x.fillStyle="#ffffff";
x.arc(,,,Math.PI*/,Math.PI*/)
x.fill()
x.closePath(); //分钟刻度
for(var i=;i<;i++){
x.save()
x.beginPath();
x.lineWidth=;
x.translate(,)
x.rotate(i**Math.PI/)
x.moveTo(,)
x.lineTo(,)
x.stroke()
x.closePath();
x.restore()
} //时钟刻度
for(var a=;a<;a++){
x.save();
x.beginPath()
x.lineWidth=;
x.translate(,);
x.rotate(a**Math.PI/);
x.moveTo(,)
x.lineTo(,)
x.stroke();
x.closePath();
x.restore();
} var time=new Date();
var miao=time.getSeconds();
var fen=time.getMinutes() + miao/;
var hours=time.getHours() + fen/;
if(hours>){
hours=hours-
} x.beginPath()
x.font="20px 黑体"
x.strokeText(time.toLocaleString(),,)
x.closePath(); //时
x.save()
x.translate(,)
x.lineWidth=;
x.beginPath();
x.rotate(hours**Math.PI/)
x.moveTo(,);
x.lineTo(,-)
x.stroke()
x.closePath();
x.restore() //分
x.save()
x.beginPath();
x.translate(,)
x.lineWidth=;
x.rotate(fen**Math.PI/)
x.moveTo(,);
x.lineTo(,-)
x.stroke()
x.closePath();
x.restore() //秒
x.save()
x.beginPath();
x.translate(,)
x.lineWidth=;
x.rotate(miao**Math.PI/)
x.moveTo(,);
x.lineTo(,-)
x.stroke()
x.closePath();
x.restore() //秒针上的小圆点 x.save()
x.beginPath();
x.translate(,)
x.rotate(miao**Math.PI/)
x.fillStyle="blue";
x.arc(,-,,,Math.PI*/)
x.fill()
x.closePath();
x.restore() //中心蓝色小圆点 x.beginPath();
x.fillStyle="blue"
x.arc(,,,,Math.PI*/)
x.fill()
x.closePath(); //中心红色小圆点 x.beginPath();
x.fillStyle="red"
x.arc(,,,,Math.PI*/)
x.fill()
x.closePath(); }
setTimeout(clock,)
setInterval(clock,)
</script>
</body>
</html>
效果图: