<htmllang="en"> <head> <metacharset="UTF-8"> <title></title> <style> canvas{ display: block; margin: 0 auto; background-color: #fdffad; border: 1px solid #000; } </style> <scripttype="text/javascript"> document.addEventListener(♀DOMContentLoaded♀,function(){ var oC=document.querySelector(♀canvas♀); var gd=oC.getContext(♀2d♀); var r=oC.width/2; function drawBackground() { gd.save(); //渐变 var ra = gd.createLinearGradient(600, 0, 400, 0); ra.addColorStop(1, ♀#2dd9ff♀); ra.addColorStop(0, ♀#8c48dd♀); //表盘 gd.translate(r, r); gd.beginPath(); gd.fillStyle = ra; gd.lineWidth = 10; gd.strokeStyle = ♀#211f4e♀; gd.arc(0, 0, r-5, 0, Math.PI *2, false); gd.fill(); gd.stroke(); //数字 for (var i = 1; i < 13; i++) { var rad=i* Math.PI * 2 / 12; var x= Math.sin(rad)*(r-70); var y= -Math.cos(rad)*(r-70); gd.fillStyle= "red"; gd.font= "bold 80px Calibri"; gd.lineWidth= 1; gd.textAlign= ♀center♀; gd.textBaseline= ♀middle♀; gd.strokeText(i, x, y); } //点 for (var i= 0; i < 60; i++) { gd.beginPath(); var rad=i* Math.PI * 2 / 60; var x= Math.sin(rad)*(r-30); var y= -Math.cos(rad)*(r-30); if (i % 5 == 0) { gd.fillStyle= ♀red♀; } else { gd.fillStyle= ♀#ccc♀ } gd.lineWidth= 2; gd.arc(x, y, 6, 0, Math.PI * 2, false); gd.fill(); gd.stroke(); gd.closePath(); } } //时针 function drawHour(h,m){ gd.save(); gd.beginPath(); var rad=2*Math.PI/12*h; var mrad=2*Math.PI/12/60*m; gd.rotate(rad+mrad); gd.lineWidth=20; gd.lineCap=♀round♀; gd.moveTo(0,10); gd.lineTo(0,-r/3); gd.stroke(); gd.closePath(); gd.restore(); } //分针 function drawMinutes(m){ gd.save(); gd.beginPath(); var rad=2*Math.PI/60*m; gd.rotate(rad); gd.lineWidth=10; gd.lineCap=♀round♀; gd.moveTo(0,10); gd.lineTo(0,-r/2); gd.stroke(); gd.closePath(); gd.restore(); } //秒针 function drawSeconds(s){ gd.save(); gd.beginPath(); var rad=2*Math.PI/60*s; gd.rotate(rad); gd.fillStyle=♀red♀; gd.moveTo(-2,20); gd.lineTo(2,20); gd.lineTo(1,-r+100); gd.lineTo(-1,-r+100); gd.fill(); gd.closePath(); gd.restore(); } //圆点 function drawPoint(){ gd.beginPath(); gd.fillStyle=♀#fff♀; gd.arc(0,0,5,Math.PI*2,false); gd.fill(); } function drawClock(){ gd.clearRect(0,0,oC.width,oC.height); var oDate=newDate(); var h=oDate.getHours(); var m=oDate.getMinutes(); var s=oDate.getSeconds(); drawBackground(); drawHour(h,m); drawMinutes(m); drawSeconds(s); drawPoint(); gd.restore(); } drawClock(); setInterval(drawClock,1000); },false); </script> </head> <body> <canvaswidth="800"height="800"></canvas> </body> </html>