H5 canvas圆形的时钟

   今天用H5中的canvas标签做一个时钟,H5中有很多好用的新增标签,真的很不错。

   1.canvas标签介绍

           <canvas> 标签定义图形,比如图表和其他图像,你必须使用脚本来绘制图形。在画布上(Canvas)画一个红色矩形,渐变矩形,彩色矩形,和一些彩色的文字。

                

          HTML5 <canvas> 元素用于图形的绘制,通过脚本 (通常是JavaScript)来完成.不过不是所有的浏览器都支持这个标签的,支持的有谷歌4.0,ie9.0,火狐2.0等


 

   2.时钟的绘制第一步

        在html中添加以下代码,一个宽高都是100的画布。

<canvas id="myCanvas" width="100" height="100"></canvas>

 3.用js开始绘制钟表

<script type="text/javascript">
     var myCanvas = document.getElementById('myCanvas');
     var c = myCanvas.getContext('2d');
     function clock(){
         c.clearRect(0,0,100,100);
         var data = new Date();
         var sec =data.getSeconds();
         var min =data.getMinutes();
         var hour=data.getHours();

         c.save();
         c.translate(50,50);
         c.rotate(-Math.PI/2);
         //分钟刻度线
         for(var i=0;i<60;i++){    //画12个刻度线
             c.beginPath();
             c.strokeStyle = "#f00";
             c.lineWidth = 1 ;
             c.moveTo(45,0);
             c.lineTo(40,0);
             c.stroke();
             c.rotate(Math.PI/30); //每个6deg画一个时钟刻度线
             c.closePath();
         }
         //时钟刻度线
         for(var i=0;i<12;i++){    //画12个刻度线
             c.beginPath();
             c.strokeStyle = "#000";
             c.lineWidth = 2 ;
             c.moveTo(45,0);
             c.lineTo(40,0);
             c.stroke();
             c.rotate(Math.PI/6); //每个30deg画一个时钟刻度线
             c.closePath();
         }
         //外表盘
         c.beginPath();
         c.strokeStyle = "pink";
         c.arc(0,0,55,0,Math.PI*2);
         c.lineWidth = 16 ;
         c.stroke();
         c.closePath();

         //画时针
         hour = hour>12?hour-12:hour;
//                console.log(hour);
         c.beginPath();
         c.save();
         c.rotate(Math.PI/6*hour+Math.PI/6*min/60+Math.PI/6*sec/3600);
         c.strokeStyle = "yellowgreen";
         c.lineWidth = 4 ;
         c.moveTo(-25,0);
         c.lineTo(40,0);
         c.stroke();
         c.restore();
         c.closePath();


         //画分针
//                console.log(min);
         c.beginPath();
         c.save();
         c.rotate(Math.PI/30*min+Math.PI/30*sec/60);
         c.strokeStyle = "springgreen";
         c.lineWidth = 3 ;
         c.moveTo(-15,0);
         c.lineTo(40,0);
         c.stroke();
         c.restore();
         c.closePath();


         //画秒针
         c.beginPath();
         c.save();
         c.rotate(Math.PI/30*sec);
         c.strokeStyle = "red";
         c.lineWidth = 2 ;
         c.moveTo(-20,0);
         c.lineTo(40,0);
         c.stroke();
         c.restore();
         c.closePath();

         c.restore();
     }
     clock();
     setInterval(clock,100);
 </script>

   


   4.得到下图的效果

         

         时钟已经画完了,关于形状和颜色可以自己再修改的。这个标签的很多使用方法我就不一一的说了,下面这个地址,大家可以查看的                     http://www.runoob.com/html/html5-canvas.html

       

原文地址:https://www.cnblogs.com/xiaonannan/p/6815916.html