Draw the dial

1) First, draw two circles as the dial

2) Then, add a time scale to the dial

3) Finally, add “hands” (hour, minute, second hand) and a center, as well as text to the dial

4) Clear the canvas, get the system time and encapsulate it

5) Then call

1. Effect picture:



2. The code is as follows:

<! DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> #cav{ display:block; margin:0 auto; background-color:#f2f2f2; } </style> </head> <body> <canvas width="800" height="800" id="cav"></canvas> <script type="text/javascript" Var CTX = cav.getcontext ('2d') function fun(){ctx.clearrect (0,0,800,800) var ctx.clearrect (0,0,800,800) var timeObj=new Date(); Var hour= timeobj.gethours (); Hours var. Min = timeObj getMinutes (); Minute var second = timeObj getSeconds (); Number of seconds the console. The log (" hour: "+ hour +" min: "+ min +" seconds: "+ second); Dial CTX. BeginPath (); ctx.strokeStyle="#cfd1ce"; ctx.lineWidth=5; 400300200,0,360 CTX. Arc (false); ctx.stroke(); ctx.closePath(); For (var I =0; i<12; i++){ ctx.save(); CTX. Translate (400300); ctx.beginPath(); ctx.rotate(Math.PI/6*i) ctx.fillStyle="#000000"; CTX. FillRect (170-5, 10) CTX. ClosePath (); ctx.restore(); } for(var I =0; i<60; i++){ ctx.save(); CTX. Translate (400300); ctx.beginPath(); ctx.rotate(Math.PI/30*i) ctx.fillStyle="#000000"; CTX. FillRect (180, - 3,10,6) CTX. ClosePath (); ctx.restore(); } the second hand CTX. The save (); CTX. Translate (400300); ctx.rotate(Math.PI/30*second) ctx.beginPath(); ctx.strokeStyle="#575757"; ctx.lineWidth=4; CTX. MoveTo (0, 15); ctx.lineTo(0,-150); ctx.stroke(); ctx.closePath(); ctx.restore(); Minute hand CTX. The save (); CTX. Translate (400300); ctx.rotate(Math.PI/30*min) ctx.beginPath(); ctx.strokeStyle="#575757"; ctx.lineWidth=6; CTX. MoveTo (0, 10); ctx.lineTo(0,-110); ctx.stroke(); ctx.closePath(); ctx.restore(); Clockwise CTX. The save (); CTX. Translate (400300); ctx.rotate(Math.PI/6*hour) ctx.beginPath(); ctx.strokeStyle="#575757"; ctx.lineWidth=6; CTX. MoveTo (0, 10); ctx.lineTo(0,-60); ctx.stroke(); ctx.closePath(); ctx.restore(); Dial center ctx.save(); CTX. Translate (400300); ctx.beginPath(); ctx.fillStyle="#000000"; CTX. Arc (0,0,8,0,360, false); ctx.fill(); ctx.closePath(); ctx.restore(); Text CTX. BeginPath (); ctx.fillStyle="#333333"; CTX. The font = "30 px song typeface blod"; CTX. FillText (" Defend Your Time ", 280260); ctx.closePath(); } fun(); How often does the timer (function name, time) call the previous function setInterval(fun,1000) </script> </body> </ HTML >Copy the code

3, dial can be obtained according to the time of their own rotation.