js Canvas實現圓形時鐘教程,jscanvas圓形時鐘

來源:互聯網
上載者:User

js Canvas實現圓形時鐘教程,jscanvas圓形時鐘

閱讀本文需要一點關於canvas基本用法的基礎,本文執行個體為大家分享了HTML5 Canvas實現圓形時鐘簡易教程

第一步:建立一個最簡單的html檔案,並且在<body>標籤中定義元素canvas。

canvas.html 

<html> <head>  <title>Canvas clock tutorial</title> </head> <body>  <canvas id="clock" width="400" height="400"></canvas> </body></html>

 在這一步完成後,用瀏覽器開啟canvas.html,你會發現什麼都看不到,這是因為我們沒有在canvas上繪製任何東西,同時也沒有為其定義邊界。

在canvas .html中為<canvas>添加css樣式屬性: 

<html> <head>  <title>Canvas clock tutorial</title>  <style type="text/css">   canvas { border: 1px solid black; }  </style> </head> <body>  <canvas id="clock" width="400" height="400"></canvas> </body></html> 

這樣,我們就能看到<canvas>的輪廓。 

當沒有設定寬度和高度的時候,canvas會初始化寬度為300像素和高度為150像素。該元素可以使用CSS來定義大小,但在繪製時映像會伸縮以適應它的架構尺寸:如果CSS的尺寸與初始畫布的比例不一致,它會出現扭曲。

注意: 如果你繪製出來的映像是扭曲的, 嘗試在<canvas>的屬性中明確規定寬和高,而不是使用CSS。 

第二步:建立實現繪製圓形時鐘邏輯的draw.js檔案,進行初始化工作。

毫無疑問,要實現時鐘,就需要擷取系統時間。 

在js文法中,可以利用Date()來即時擷取時間。
 var currentTime = new Date();

隨後,要掌握的是canvas繪製圓形的函數:
 arc(x, y, radius, startAngle, endAngle, anticlockwise)該方法表示畫一個以(x,y)為圓心的、以radius為半徑的圓弧(圓),從startAngle開始到endAngle結束,按照anticlockwise給定的方向(預設順時針(true))來產生。
 其中stratAngle和endAngle的單位並不是我們所熟悉的角度單位,而是弧度單位。一個完整的圓跨弧度2π。 

在canvas的座標系中,是以x軸正方向所在的方向為0弧度。時鐘指標按順時針方向轉,以2π為一個周期,因此如所示,時鐘指標,是從(-1/2)*π位置開始走的。 

目前時間的弧度計算方式如下:

 //將一個刻度12等分,對12求餘是因為Date().getHours將返回24小時制的小時。hour = (currentTime.getHours() % 12 ) * (2 * Math.PI /12); //MINUTE 一圈60等分minute = (currentTIme.getMinutes) * (2* Math.PI / 60); //SECOND 一圈60等分second = (currentTime.getSeconds) * (2 * Math.PI / 60); 

由於在canvas中時鐘圓從(-1/2)*π開始走,因此我們還需要給它們加上(-1/2)*π的起始位移量。 

初步得到draw.js:
 

function draw() { //canvas繪畫的前提工作 var canvas = document.getElementById('clock'); var currentTime = new Date(); var hour = (currentTime.getHours()%12) * Math.PI/6; var minute = currentTime.getMinutes() * Math.PI/30; var second = currentTime.getSeconds() * Math.PI/30; hour = hour - Math.PI * (1/2); minute = minute - Math.PI * (1/2); second = second - Math.PI * (1/2); if (canvas.getContext){  var ctx = canvas.getContext('2d');  ctx.beginPath();  ctx.arc(200,200,50,Math.PI*(-1/2),hour,false);  ctx.moveTo(200,100);  ctx.arc(200,200,100,Math.PI*(-1/2),minute,false);  ctx.moveTo(200,50);  ctx.arc(200,200,150,Math.PI*(-1/2),second,false);  ctx.stroke(); }}

同時在canvas.html中 加入draw.js的引用。 

<html> <head>  <title>Canvas clock tutorial</title>  <style type="text/css">   canvas { border: 1px solid black; }  </style>  <script src="draw.js" type="text/javascript"></script> </head> <body onload="draw();">  <canvas id="clock" width="400" height="400"></canvas> </body></html> 

在完成了第二步之後,我們可以看到一個目前時間的圓形時鐘輪廓。那麼接下來,就是讓它動起來! 

第三步:使用requestAnimationFrame()方法讓時鐘動起來。 

requestAnimationFrame()的執行頻率是1秒60幀,使用者可以在requestAnimationFrame定義事件,使其在每一幀中重複、迭代完成相應的事件。 

在我們這個案例中,每一幀裡面requestAnimationFrame要做的事情很簡單,為目前時間的三個參數(時針、分針、秒針)添加增量,然後重新繪製時鐘。 

根據一秒60幀的頻率,那麼second在1幀裡面的增量是:2*π / 60 / 60 = π / 1800; 

minute在一幀裡面的增量是second增量的60分之一;hour在一幀裡面的增量是minute的12分之1。
 

另外:當hour、minute、second任一一個變數到達3/2*π後,意味著完成了一個周期,就要重新初始化為(-1/2)*π,否則會覆蓋繪製成一個圓。 

由此得到:requestAnimationFrame()函數中,hour,minute,second的更新過程如下: 

   var s = Math.PI / 1800;   var m = s / 60;   var h = m / 12;   second = second + s;   minute = minute + m;   hour = hour + h;   if(second >= Math.PI * (3/2)){    second = Math.PI * (-1/2);   }   if(minute >= Math.PI * (3/2)){    minute = Math.PI * (-1/2);   }   if(second >= Math.PI * (3/2)){    second = Math.PI * (-1/2);   }</span>

 更新draw.js的完整代碼如下:

function draw() { var canvas = document.getElementById('clock'); var currentTime = new Date(); var hour = (currentTime.getHours()%12) * Math.PI/6; var minute = currentTime.getMinutes() * Math.PI/30; var second = currentTime.getSeconds() * Math.PI/30; hour = hour - Math.PI * (1/2); minute = minute - Math.PI * (1/2); second = second - Math.PI * (1/2); if (canvas.getContext){  var ctx = canvas.getContext('2d');  var s = Math.PI / 1800;  var m = s / 60;  var h = m / 12;  var rotate = requestAnimationFrame(step);  function step(){   second = second + s;   minute = minute + m;   hour = hour + h;   if(second >= Math.PI * (3/2)){    second = Math.PI * (-1/2);   }   if(minute >= Math.PI * (3/2)){    minute = Math.PI * (-1/2);   }   if(second >= Math.PI * (3/2)){    second = Math.PI * (-1/2);   }   ctx.clearRect(0, 0, 400 , 400);   ctx.beginPath();   ctx.arc(200,200,50,Math.PI*(-1/2),hour,false);   ctx.moveTo(200,100);   ctx.arc(200,200,100,Math.PI*(-1/2),minute,false);   ctx.moveTo(200,50);   ctx.arc(200,200,150,Math.PI*(-1/2),second,false);   ctx.stroke();   requestAnimationFrame(step);  } }}

到這步為止,我們已經得到了一個會動的圓形時鐘,接下來,我們為其添加上指標。 

第四步*:添加時針、分針、秒針。 

JS為我們提供了Math.cos() 、Math.sin() 計算指標到達的位置,它們所接收參數的單位也都是弧度。

 function draw() { var canvas = document.getElementById('clock'); var currentTime = new Date(); var hour = (currentTime.getHours()%12) * Math.PI/6; var minute = currentTime.getMinutes() * Math.PI/30; var second = currentTime.getSeconds() * Math.PI/30; hour = hour - Math.PI * (1/2); minute = minute - Math.PI * (1/2); second = second - Math.PI * (1/2); if (canvas.getContext){  var ctx = canvas.getContext('2d');  var s = Math.PI / 1800;  var m = s / 60;  var h = m / 12;  var rotate = requestAnimationFrame(step);  function step(){   second = second + s;   minute = minute + m;   hour = hour + h;   if(second >= Math.PI * (3/2)){    second = Math.PI * (-1/2);   }   if(minute >= Math.PI * (3/2)){    minute = Math.PI * (-1/2);   }   if(second >= Math.PI * (3/2)){    second = Math.PI * (-1/2);   }   //秒針的終點   xs = 150 * Math.cos(second) + 200;   ys = 150 * Math.sin(second) + 200;   //分針的終點   xm = 100 * Math.cos(minute) + 200;   ym = 100 * Math.sin(minute) + 200;   //時針的終點   xh = 50 * Math.cos(hour) + 200;   yh = 50 * Math.sin(hour) + 200;   ctx.clearRect(0, 0, 400 , 400);   ctx.beginPath();   //繪製指標   ctx.moveTo(200,200);   ctx.lineTo(xs,ys);   ctx.moveTo(200,200);   ctx.lineTo(xm,ym);   ctx.moveTo(200,200);   ctx.lineTo(xh,yh);   //繪製圓形輪廓   ctx.moveTo(200,150);   ctx.arc(200,200,50,Math.PI*(-1/2),hour,false);   ctx.moveTo(200,100);   ctx.arc(200,200,100,Math.PI*(-1/2),minute,false);   ctx.moveTo(200,50);   ctx.arc(200,200,150,Math.PI*(-1/2),second,false);   ctx.stroke();   requestAnimationFrame(step);  } }}

嗯嗯,雖然指標是畫出來了,都是我略感後悔,因為感覺太醜了。從審美學角度而言,帶指標時鐘就應該是個全圓輪廓的時鐘。不知道讀者有沒有同感。我決定在第五步中把第四步回退了。 

第五步:個人化、美化、自訂你的時鐘。 

html5的canvas畫布,提供了多種樣式屬性,如線條顏色、線條寬度等等。 

為了提高代碼的可重用性,我們將畫圓的代碼抽象成一個函數。

 function draw() { var canvas = document.getElementById('clock'); var currentTime = new Date(); var hour = (currentTime.getHours()%12) * Math.PI/6; var minute = currentTime.getMinutes() * Math.PI/30; var second = currentTime.getSeconds() * Math.PI/30; hour = hour - Math.PI * (1/2); minute = minute - Math.PI * (1/2); second = second - Math.PI * (1/2); if (canvas.getContext){  var ctx = canvas.getContext('2d');  var s = Math.PI / 1800;  var m = s / 60;  var h = m / 12;  var rotate = requestAnimationFrame(step);  function step(){   second = second + s;   minute = minute + m;   hour = hour + h;   if(second >= Math.PI * (3/2)){    second = Math.PI * (-1/2);   }   if(minute >= Math.PI * (3/2)){    minute = Math.PI * (-1/2);   }   if(second >= Math.PI * (3/2)){    second = Math.PI * (-1/2);   }   ctx.clearRect(0, 0, 400 , 400);   ctx.beginPath();   //繪製圓形輪廓   drawCircle(ctx, 100, hour, '#99ff00');   drawCircle(ctx, 120, minute, '#99ff66');   drawCircle(ctx, 140, second, '#66cc66');   requestAnimationFrame(step);  } }}function drawCircle(ctx, radius ,endAngle, color){ ctx.beginPath(); ctx.moveTo(200,200-radius); ctx.strokeStyle = color; ctx.lineWidth = 20; ctx.arc(200,200,radius,Math.PI*(-1/2),endAngle,false); ctx.stroke();} 

第六步(後續添加):為時鐘添加數字指數。 

具體做法為多增加一個畫布canvas元素。既然我們已經能從Date()中擷取時間,那麼顯示數值的來源不成問題。讀者唯一需要知道的就是利用setInterval(thingstodo(),interval)方法來實現每秒更新一次指數。 

修改後的canvas.html 

<html> <head>  <title>Canvas clock tutorial</title>  <style type="text/css">   canvas { border: 1px solid black; }   #display {position: absolute; top:8; left:8;}  </style>  <script src="draw.js" type="text/javascript"></script> </head> <body onload="draw();">  <canvas id="clock" width="400" height="400"></canvas>  <canvas id="display" width="400" height="400"></canvas> </body></html>

 修改後的draw.js

function draw() { var canvas = document.getElementById('clock'); var displayCanvas = document.getElementById('display'); var currentTime = new Date(); var hour = (currentTime.getHours()%12) * Math.PI/6; var minute = currentTime.getMinutes() * Math.PI/30; var second = currentTime.getSeconds() * Math.PI/30; hour = hour - Math.PI * (1/2); minute = minute - Math.PI * (1/2); second = second - Math.PI * (1/2); if (canvas.getContext){  var ctx = canvas.getContext('2d');  var ctxD = displayCanvas.getContext('2d');  showDisplay(ctxD, currentTime);  var s = Math.PI / 1800;  var m = s / 60;  var h = m / 12;  var rotate = requestAnimationFrame(step);  function step(){   second = second + s;   minute = minute + m;   hour = hour + h;   if(second >= Math.PI * (3/2)){    second = Math.PI * (-1/2);   }   if(minute >= Math.PI * (3/2)){    minute = Math.PI * (-1/2);   }   if(second >= Math.PI * (3/2)){    second = Math.PI * (-1/2);   }   ctx.clearRect(0, 0, 400 , 400);   ctx.beginPath();   //繪製圓形輪廓   drawCircle(ctx, 100, hour, '#99ff00');   drawCircle(ctx, 120, minute, '#99ff66');   drawCircle(ctx, 140, second, '#66cc66');   requestAnimationFrame(step);  } }}function drawCircle(ctx, radius ,endAngle, color){ ctx.beginPath(); ctx.moveTo(200,200-radius); ctx.strokeStyle = color; ctx.lineWidth = 20; ctx.arc(200,200,radius,Math.PI*(-1/2),endAngle,false); ctx.stroke();}function showDisplay(ctx, date){ var h = date.getHours(),m = date.getMinutes(),s = date.getSeconds(); //計時文字樣式  ctx.font = "13px Sans-Serif"; ctx.textAlign = "center"; ctx.strokeText(h+":"+m+":"+s,200,200); var timmer = setInterval(function(){  s++;  if(s>=60){   m++;   s=0;  }  if(m>=60){   h++;   m=0;  }  if(h>=24){   h=0;  }  ctx.clearRect(0,0,400,400);  ctx.strokeText(h+":"+m+":"+s,200,200); },1000);}

 最終成果圖如下:

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.