<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>时钟</title> </head> <body> <div> <canvas id="canvas" width="800" height="600"></canvas> </div> <script type="text/javascript"> let canvas = document.getElementById("canvas"); let ctx = canvas.getContext("2d"); timepiece(); setInterval(timepiece,1000); function timepiece(){ let date = new Date();//创建事件对象获取当前时间 let hour = date.getHours();//获取当前小时 let min = date.getMinutes();//获取当前分钟 let sec = date.getSeconds();//获取当前秒 hour = hour>12 ? hour-12 : hour; /*if(hour>12){ hour = hour - 12; }else{ hour = hour; }*/ ctx.clearRect(0,0,800,600); ctx.save(); //绘制表框 ctx.beginPath(); ctx.lineWidth = 3; ctx.strokeStyle = 'gray'; ctx.arc(200,200,150,0,2*Math.PI,false); /* let color = ctx.createRadialGradient(200,200,50,200,200,100); color.addColorStop(0.0,"lightgreen"); color.addColorStop(1.0,"lightblue"); ctx.fillStyle = color; ctx.fill();*/ ctx.stroke(); ctx.restore(); ctx.save(); ctx.translate(200,200); for(let i = 0;i<60;i++){ if(i%5==0){ ctx.beginPath(); ctx.moveTo(0,140); ctx.lineTo(0,148); ctx.lineWidth=5; ctx.strokeStyle = 'red'; ctx.stroke(); ctx.rotate(Math.PI/30); }else{ ctx.beginPath(); ctx.moveTo(0,143); ctx.lineTo(0,148); ctx.lineWidth=1; ctx.strokeStyle = 'pink'; ctx.stroke(); ctx.rotate(Math.PI/30); } } ctx.restore(); //绘制秒针 ctx.save(); ctx.translate(200,200); ctx.rotate(sec*Math.PI/30) ctx.beginPath(); ctx.moveTo(0,30); ctx.lineTo(0,-140); ctx.strokeStyle = 'red'; ctx.stroke(); ctx.restore(); //绘制分针 ctx.save(); ctx.translate(200,200); ctx.rotate(sec*Math.PI/1800 + min*Math.PI/30)//每一秒分成60份,秒针走一秒分针走60分之1,sec*(6*Math.PI/180)/60 ctx.beginPath(); ctx.moveTo(0,20); ctx.lineTo(0,-120); ctx.lineWidth = 2; ctx.strokeStyle = 'yellow'; ctx.stroke(); ctx.restore(); //绘制时针 ctx.save(); ctx.translate(200,200); ctx.rotate(min*Math.PI/360 + hour*Math.PI/6);//每一小时走过5个刻度线,60分钟,30deg,分成60份,30deg/60 ctx.beginPath(); ctx.moveTo(0,10); ctx.lineTo(0,-100); ctx.strokeStyle = 'black'; ctx.stroke(); ctx.restore(); } </script> </body> </html
效果: