最近公司銷售有業務須要,要修改百度頁面的北京時間,拍照和錄視頻。因此參考百度原代碼,作了一些註釋。在下一篇文章中,我會用另外一種方法,也寫出這個效果。html
效果預覽:https://codepen.io/andy-js/pen/wvBPgBW
右鍵打開新窗口預覽效果更好哦!canvas
直接上代碼。微信
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>andy-js:模仿百度北京時間時鐘</title> <style> *{margin:0;padding:0} #box{width:100px;height:100px;position: relative;margin:200px auto;background:linear-gradient(#0b6ec2,#6aa9e1)} #c1{position: absolute;top:50%;left:50%;z-index: 1;margin:-33px 0 0 -33px;} #c2{position: absolute;top:50%;left:50%;z-index: 2;margin:-33px 0 0 -33px;} </style> </head> <body> <div id="box"> <canvas id="c1" width="66" height="66"></canvas> <canvas id="c2" width="66" height="66"></canvas> </div> <script> var oC1=document.getElementById('c1'); //錶盤 var oC2=document.getElementById('c2'); //指針 var ctx2 = oC2.getContext("2d"),ctx1 = oC1.getContext("2d"); //1.先畫表盤 var lineLength, //標線長度 radius = oC1.offsetWidth / 2; ctx1.lineWidth = 1; //線的寬度 ctx1.translate(radius, radius); //從新映射畫布上的 (0,0) 位置 映射到畫布正中間 for (var i = 0; i < 60; i++) { lineLength = 4; //默認長度 ctx1.strokeStyle = "rgba( 255, 255, 255, 0.3 )"; //默認標線顏色,1234淡一點 if ( i % 5 == 0) { lineLength = 8, //每遇五、0長一點 ctx1.strokeStyle = "#fff"; }; ctx1.beginPath(); //起始一條路徑 ctx1.moveTo(0, lineLength - radius); //畫直線的起點,好比第一條線是0點的位置,如今中心點已是00座標,因此第一條線應該是X=0,Y=-(33-8); 33是半徑 ctx1.lineTo(0, -radius); //而後一直畫到半徑最邊上 ctx1.stroke(); //繪製已定義的路徑 ctx1.closePath(); //關閉路徑 ctx1.rotate(Math.PI / 30); //旋轉當前畫布 旋轉一分鐘 Math.PI=180度=30分鐘=半圓 }; render(); //2.打開頁面默認顯示 setInterval(render,1000); //3.每秒種重繪一次 function render(){ ctx2.clearRect(0, 0, 2 * radius, 2 * radius); //每次都清空畫布 從新畫 var oDate=new Date(); //獲取當前時間 var hour = oDate.getHours(), //小時 minute = oDate.getMinutes(), //分 second =oDate.getSeconds(); //秒 hour > 12 && (hour -= 12); hour += minute / 60; minute += second / 60; draw(3, "#fff", Math.PI / 6 * hour, -16); //時針 draw(2, "#fff", Math.PI / 30 * minute, -22); //分針 draw(1, "#d93c3c", Math.PI / 30 * second, -24);//秒針 }; function draw(lineWidth, strokeStyle, rotate, end) { ctx2.save(), //保存當前的畫布狀態 保存映射和旋轉以前的狀態 ctx2.lineWidth = lineWidth, //線條寬度 ctx2.strokeStyle = strokeStyle, //顏色 ctx2.translate(radius, radius), //從新映射畫布上的 (0,0) 位置 映射到畫布正中間 ctx2.rotate(rotate), //旋轉 ###重點是這裏的旋轉 ctx2.beginPath(), ctx2.moveTo(0, 6), //三根指針老是從00位置另外一端多出來一小段 ctx2.lineTo(0, end), //三根指針的長度 ctx2.stroke(), ctx2.closePath(), ctx2.restore(); //返回以前保存過的路徑狀態和屬性 }; /* ###旋轉講解 前面說過 Math.PI=180度=30分鐘=半圓 因此 Math.PI / 30 等於 1分鐘的角度 1.second秒針自己就是1-60之間,因此這裏很好理解 當前是多少秒就旋轉多少角度 2.時鐘 Math.PI/6= 30分鐘/6=半圓/6 = 每五分鐘 = 每1小時的角度 咱們在前面已經經過 hour > 12 && (hour -= 12); 將時針的數值固定在 <=12 再經過 hour += minute / 60; 獲得基數爲12的相應的時間比例 由於鐘錶的一圈有12個時間 再用咱們獲得的 每1小時的角度 * 相應的比例 3.分鐘 與時鐘同理 */ </script> </body> </html>