html5 canvas制作的简单时钟效果
<html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <style type="text/css"> body{background:#ccc;} #canvas{background:#fff;} </style> <script type="text/javascript"> window.onload=function(){ var myCanvas=document.getElementById('canvas'); var ctx=myCanvas.getContext('2d'); function drawClock() { var oDate=new Date(); var oHours=oDate.getHours(); var oMinutes=oDate.getMinutes(); var oSeconds=oDate.getSeconds(); var SecondsValue=(-90+oSeconds*6)*Math.PI/180; var MinutesValue=(-90+oMinutes*6)*Math.PI/180; var HoursValue=(-90+oHours*30+oMinutes/2)*Math.PI/180; var x=200; var y=200; var r=150; ctx.clearRect(0,0,400,400); function ClockArc(m,n) { ctx.lineWidth=1; ctx.beginPath(); ctx.strokeStyle="black"; for(i=0;i<60;i++) { ctx.moveTo(x,y); ctx.arc(x,y,r,i*m*Math.PI/180,(i+1)*m*Math.PI/180,false); } ctx.closePath(); ctx.stroke(); ctx.fillStyle="white"; ctx.beginPath(); ctx.moveTo(x,y); ctx.arc(x,y,r*n/20,0,360*Math.PI/180,false); ctx.closePath(); ctx.fill(); } function dateClick(j,l,w) { ctx.strokeStyle="#334214"; ctx.lineWidth=w; ctx.beginPath(); ctx.moveTo(x,y); ctx.arc(x,y,r*l/20,j,j,false); ctx.closePath(); ctx.stroke(); } //表盘 ClockArc(6,19); //表盘整点 ClockArc(30,18); //秒针 dateClick(SecondsValue,17.5,1); //分针 dateClick(MinutesValue,15.5,2); //时针 dateClick(HoursValue,13.5,3); } setInterval(drawClock,1000); drawClock(); }; </script> </head> <body> <canvas id="canvas" width="400" height="400"></canvas> </body> </html>