首页 > 代码库 > canvas之动态时钟

canvas之动态时钟

 

 1 function showTime(){ 2         var can=document.getElementById("canvas"); 3         var c=can.getContext("2d");//定义2D画布 4         can.width="1000"; 5         can.height="600"; 6         //平移确定中心 7         c.translate(500,300); 8         //获取本地时间 9         var sum=new Date();10         var sh=sum.getHours();11         var sm=sum.getMinutes();12         var se=sum.getSeconds();13             sh=sh>=12?sh-12:sh;14         //时针15         c.save();16         c.rotate(sh*(Math.PI/6)+sm*(Math.PI/6/60)+se*(Math.PI/6/60/60));//转成时针的弧度:时+分+秒17         c.moveTo(0,30);18         c.lineTo(0,-115);19         c.lineWidth=15;20         c.lineCap="round";21         c.stroke();22         c.restore();23         //分针24         c.save();//防止互相干扰25         c.rotate(sm*(Math.PI/6/5)+se*(Math.PI/6/5/60));26         c.moveTo(0,35);27         c.lineTo(0,-135);28         c.lineWidth=12;29         c.lineCap="round";30         c.stroke();31         c.restore();32         33         //秒针34            c.beginPath();35         c.fillStyle="#f00";36         c.arc(0,0,15,0,2*Math.PI);37         c.fill();38 39         c.save();40         c.rotate(se*(Math.PI/30));41         c.beginPath();42           c.strokeStyle="#f00";43           c.lineWidth=5;44           c.moveTo(0,45);45           c.lineTo(0,-140);46           c.stroke();47           c.restore();48          49          //秒间隔的点//虚线画法//遇到跟随顺势针旋转问题,分别测试将时、分、秒旋转方向改为反向,发现改分针时,出现跟随的方向也反转,确定是受分针转动影响50          c.save();51           c.beginPath();52           c.arc(0,0,200,0,2*Math.PI);53         c.setLineDash([5,2*Math.PI*200/60-5]);//周长除以60减去线粗554         c.lineDashOffset="2.5";//修正线粗带来的偏差55         c.lineWidth=5;56         c.lineCap="butt";57         c.strokeStyle="#000";58         c.stroke();59         c.restore();60         //时点61         c.save();62         c.beginPath();63         c.arc(0,0,195,0,2*Math.PI);64         c.setLineDash([8, 195*2*Math.PI/12-8]);65         c.lineDashOffset="4";66         c.lineWidth=20;67         c.stroke();68         c.restore();69         //时钟数字70           var x;71           var y;72           var n=-1;73           var array=[3,4,5,6,7,8,9,10,11,12,1,2];74           for(var m=0;m<12;m++){75               n+=1;76               x=170*(Math.cos(Math.PI/6*n))-8;//后面减去8、加上10,修正中心77               y=170*(Math.sin(Math.PI/6*n))+10;78               c.beginPath();79               c.fillStyle="#000";80               c.font="24px 微软雅黑";81               //10、11、12占两位需修正不对齐中心问题,这里只修正12,n==982               if(n==9){83                   x=x-5;84               }85               c.fillText(array[m],x,y);86           }87         //加个钟盘样式好看点88         c.beginPath();89         c.arc(0,0,220,0,2*Math.PI);90         c.strokeStyle="#325fa2";91         c.lineWidth=10;92         c.stroke();93     }94         showTime();    95         setInterval(showTime,1000);
    

 

canvas之动态时钟