javascript canvas實現簡易時鐘例子
更新時間:2020年09月05日 11:52:52 作者:肥羊7崽
這篇文章主要為大家詳細介紹了javascript canvas實現簡易時鐘例子,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了javascript canvas實現簡易時鐘的具體代碼,供大家參考,具體內容如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>鐘表</title> <script type="text/javascript"> window.onload=function(){ //1.獲取畫布 var canvas=document.getElementById("canvas"); //2.獲取上下文對象(獲取畫筆) var cx=canvas.getContext("2d"); //3.設置畫筆樣式 function clock(){ cx.fillStyle="tomato"; //4.繪制圖形 //繪制表盤 cx.beginPath(); //繪制圓形 cx.arc(300,300,200,0,Math.PI*2);//設置圓 arc(x,y,r,begin,end,c);x,y:圓的圓的圓心坐標 r:圓的半徑 begin,end:開始角度和結束角度;Math.PI=180 Math.PI/180=1度 c:是否按照逆時針進行繪制true:按照逆時 false:順時針 cx.closePath();//關閉路徑 cx.fill();// //繪制時刻度 cx.lineWidth=2; cx.strokeStyle="black"; for(var i=0;i<12;i++){ cx.save(); cx.translate(300,300);//形移 cx.rotate(i*(Math.PI/6)); cx.beginPath(); cx.moveTo(0,-180); cx.lineTo(0,-200); cx.stroke(); cx.closePath(); cx.fillStyle="black";//繪制數字 cx.font="16px blod"; cx.rotate(Math.PI/6); cx.fillText(i+1,-6,-220);//文字 cx.restore(); } //繪制分刻度 for(var i=0;i<60;i++){ cx.save(); cx.translate(300,300); cx.rotate(i*(Math.PI/30)); cx.beginPath(); cx.moveTo(0,-190); cx.lineTo(0,-200); cx.stroke(); cx.closePath(); cx.restore(); } //獲取當前時間 var today=new Date(); var hour=today.getHours(); var min=today.getMinutes(); var sec=today.getSeconds(); hour=hour+min/60; //繪制時針 cx.lineWidth=4; cx.save(); cx.translate(300,300); cx.beginPath(); cx.rotate(hour*(Math.PI/6));//旋轉 cx.moveTo(0,10); cx.lineTo(0,-130); cx.closePath(); cx.stroke(); cx.restore(); //回滾 //繪制分針 cx.lineWidth=2; cx.save(); cx.translate(300,300); cx.beginPath(); cx.rotate(min*(Math.PI/30)); cx.moveTo(0,10); cx.lineTo(0,-160); cx.closePath(); cx.stroke(); cx.restore(); //回滾 //繪制秒針 cx.lineWidth=1; cx.strokeStyle="black"; cx.save(); cx.translate(300,300); cx.beginPath(); cx.rotate(sec*(Math.PI/30)); cx.moveTo(0,10); cx.lineTo(0,-160); cx.closePath(); cx.stroke(); cx.restore(); //繪制交叉處 cx.fillStyle='#ccc'; cx.strokeStyle="red"; cx.save(); cx.translate(300,300); cx.beginPath(); cx.beginPath(); cx.arc(0,0,4,0,Math.PI*2); cx.closePath(); cx.fill(); cx.closePath(); cx.stroke(); cx.restore(); setTimeout(clock,1000); } // setInterval(clock,1000); clock(); } </script> </head> <body> <canvas id="canvas" width="1300px" height="600px" style="background-color: #ccc;"></canvas> </body> </html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。