JavaScript Canvas編寫炫彩的網頁時鐘
阿新 • • 發佈:2020-11-26
本文例項為大家分享了JavaScript Canvas編寫炫彩網頁時鐘的具體程式碼,供大家參考,具體內容如下
只是利用了Canvas製作的。
示意圖如下:
<!DOCTYPE html> <html> <head> <meta http-equiv = "Content-Type" content = "text/html"; charsert = "utf-8" /> <title> 網頁時鐘 </title> </head> <body> <h2> Web時鐘 </h2> <canvas id = "hello" width = "400" height = "400" style = "border:1px solid black"> </canvas> <script languagetype = "text/javascript"> var myCavas = document.getElementById('hello'); var c = myCavas.getContext('2d'); function clock() { c.clearRect(0, 0, 400, 400); //獲取當前時間 var data = new Date(); //獲取秒 var sec = data.getSeconds(); //獲取分鐘 var min = data.getMinutes(); //獲取小時 var hour = data.getHours(); c.save(); c.translate(200, 200); c.rotate(-Math.PI/2); //分針刻度線 for (var i = 0; i < 60; i++) { //畫60個刻度線 c.beginPath(); c.strokeStyle = "yellowgreen"; c.lineWidth = 5; c.moveTo(117, 0); c.lineTo(120, 0); c.stroke(); //每6deg畫一個分鐘刻度線 c.rotate(Math.PI/30); c.closePath(); } //時鐘刻度線 for (var i = 0; i < 12; i++) { //畫60個刻度線 c.beginPath(); c.strokeStyle = "green"; c.lineWidth = 8; c.moveTo(100, 0); c.lineTo(120, 0); c.stroke(); //每6deg畫一個分鐘刻度線 c.rotate(Math.PI/6); c.closePath(); } //外表盤 c.beginPath(); c.strokeStyle = "pink"; c.arc(0, 0, 145, 0, Math.PI*2); c.lineWidth = 12; c.stroke(); c.closePath(); //畫時針 hour = hour > 12 ? hour-12 : hour; //console.log(hour); c.beginPath(); c.save(); //設定旋轉角度,引數是弧度,角度0-360 弧度角度*Math.PI/180 c.rotate(Math.PI/6*hour + Math.PI/6*min/60 + Math.PI/6*sec/3600); c.strokeStyle = "yellowgreen"; c.lineWidth = 4; c.moveTo(-20, 0); c.lineTo(50, 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(-30, 0); c.lineTo(70, 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(-40, 0); c.lineTo(120, 0); c.stroke(); c.restore(); c.closePath(); c.restore(); } clock(); setInterval(clock, 1000); </script> </body> </html>
更多JavaScript時鐘特效點選檢視:JavaScript時鐘特效專題
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援碼農教程。