canvas钟表

canvas是绘制图形的一个api,也可以用来制作h5小游戏

canvas时间表用到的技术点如下:

DOMobj.getContext("2d");  // 获取2D环境, 创建画布

beginPath();  // 起始一条路径,或重置当前路径

closePath();  // 创建从当前点回到起始点的路径

moveTo(x,y); //把路径移动到画布中的指定点,不创建线条

stroke(); // 绘制已定义的路径

fillStyle="#fff"; //  属性设置或返回用于填充绘画的颜色、渐变或模式。

fill(); // 填充当前绘图(路径)

arc(x,y,r,sAngle,eAngle,false); // 创建弧/曲线(用于创建圆形或部分圆);x和y是圆的中心坐标,r为半径,sAngle,eAngle 分别为起始弧度和结束弧度,最后一个参数规定是顺时针还是逆时针绘图,False = 顺时针,true = 逆时针。

弧度计算公式:360度 = 2∏,1度 = ∏/180

以下是钟表源码:

html代码:

<canvas id="cavs" width="500" height="500"></canvas>

JavaScript代码:

 1 var ocavs = document.getElementById("cavs");
 2  var ctx = ocavs.getContext("2d");
 3 
 4  function drawTime(){
 5      var x = 200;
 6      var y = 200;
 7      var r = 150;
 8      ctx.clearRect(0,0,ocavs.width,ocavs.height);
 9      var oDate = new Date();
10      var oH = oDate.getHours();
11      var oMin = oDate.getMinutes();
12      var osec = oDate.getSeconds();
13 
14      var oHvalue = (-90+oH*30+oMin/2)*Math.PI/180;
15      var oMinvalue = (-90+oMin*6)*Math.PI/180;
16      var osecvalue = (-90+osec*6)*Math.PI/180;
17 
18      ctx.beginPath();
19      for(var i=0; i<60; i++){
20          ctx.moveTo(x,y);
21          ctx.arc(x,y,r,6*i*Math.PI/180,6*(i+1)*Math.PI/180,false);
22      }
23      ctx.closePath();
24      ctx.stroke();
25 
26      ctx.fillStyle = "white";
27      ctx.beginPath();
28      ctx.moveTo(x,y);
29      ctx.arc(x,y,r*19/20,0,360*Math.PI/180,false);
30      ctx.closePath();
31      ctx.fill();
32 
33      ctx.lineWidth = 3;
34      ctx.beginPath();
35      for(var i=0; i<12; i++){
36          ctx.moveTo(x,y);
37          ctx.arc(x,y,r,30*i*Math.PI/180,30*(i+1)*Math.PI/180,false);
38      }
39      ctx.closePath();
40      ctx.stroke();
41 
42      ctx.fillStyle = "white";
43      ctx.beginPath();
44      ctx.moveTo(x,y);
45      ctx.arc(x,y,r*18/20,0,360*Math.PI/180,false);
46      ctx.closePath();
47      ctx.fill();
48 
49      ctx.lineWidth = 5;
50      ctx.beginPath();
51      ctx.moveTo(x,y);
52      ctx.arc(x,y,r*10/20,oHvalue,oHvalue,false);
53      ctx.closePath();
54      ctx.stroke();
55 
56      ctx.lineWidth = 3;
57      ctx.beginPath();
58      ctx.moveTo(x,y);
59      ctx.arc(x,y,r*14/20,oMinvalue,oMinvalue,false);
60      ctx.closePath();
61      ctx.stroke();
62 
63      ctx.lineWidth = 1;
64      ctx.beginPath();
65      ctx.moveTo(x,y);
66      ctx.arc(x,y,r*19/20,osecvalue,osecvalue,false);
67      ctx.closePath();
68      ctx.stroke();
69  }
70  setInterval(drawTime,1000);
71  drawTime();

 

posted on 2016-09-03 15:15  vivayue  阅读(169)  评论(0编辑  收藏  举报

导航