<!DOCTYPE html> <html> <head> <title>HTML5 Canvas Demo of clock</title> <script> function time(){ var mycanvas=document.getElementById("myCanvasTag"); var mycontext=mycanvas.getContext('2d'); //清空画布, mycontext.clearRect(0,0,600,500) //时钟圆圈 mycontext.beginPath(); mycontext.arc(200,200,150,0,2*Math.PI); mycontext.stroke(); //设置参数 var myDate = new Date(); mycontext.font='10px Arial' mycontext.fillText(myDate.toLocaleString(),20,20) var h=myDate.getHours(); var m=myDate.getMinutes(); var s=myDate.getSeconds(); var deg = Math.PI/180; mycontext.beginPath(); //移动旋转点 mycontext.translate(200,200) //绘制大刻度 for(var i=0;i<12;i++){ mycontext.lineWidth=2; mycontext.rotate(30*deg) mycontext.moveTo(-140,0) mycontext.lineTo(-130,0) } mycontext.stroke() //绘制小刻度 for(var i=0;i<60;i++){ mycontext.lineWidth=1; mycontext.rotate(6*deg) mycontext.moveTo(-140,0) mycontext.lineTo(-135,0) } mycontext.stroke() //绘制时针 if(h>=12){h-=12} mycontext.rotate((30*h+m/2+s/10)*deg) mycontext.lineWidth=3; mycontext.moveTo(0,10); mycontext.lineTo(0,-100) mycontext.stroke() //绘制分针 mycontext.rotate(-(30*h+m/2+s/10)*deg) mycontext.rotate((6*m+s/10)*deg) mycontext.lineWidth=2; mycontext.moveTo(0,10); mycontext.lineTo(0,-110) mycontext.stroke() mycontext.rotate(-(6*m+s/10)*deg) //绘制秒针 mycontext.rotate(6*s*deg) mycontext.lineWidth=1; mycontext.moveTo(0,-120); mycontext.lineTo(0,20) mycontext.stroke() mycontext.rotate(-6*s*deg) //初始化旋转点 mycontext.translate(-200,-200) } setInterval(time,1000) </script> </head> <body> <div style="margin-left:30px;"> <canvas id="myCanvasTag" width="500" height="500"></canvas> </div> </body> </html>
玩了一天多的canvas,写了个时钟玩,多有不足,望指教。