【前端html/js】使用canvas實現(xiàn)實時時鐘
- 代碼如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>飛宇時鐘</title>
</head>
<body>
<canvas id="canvas" width="800" height="600"></canvas>
<script type="text/javascript">
"use strict ";
function getDatetime(){
let da = new Date();
let hours = da.getHours();
hours=hours>12?hours-12:hours;
let minute = da.getMinutes();
let second = da.getSeconds();
return [hours,minute,second];
}
</script>
<script type="text/javascript">
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
// 繪制刻度函數(shù)
function scaleRender(deg,start,end,bw,color){
ctx.beginPath();
ctx.rotate(deg); // 旋轉(zhuǎn)
ctx.moveTo(start,0);
ctx.lineTo(end,0);
ctx.lineWidth=bw;
ctx.strokeStyle=color;
ctx.stroke();
ctx.closePath();
ctx.restore();
ctx.save();
}
function initClockBasicInfo(){
// 圓的中心的 x 坐標,圓的中心的 y 坐標,圓的半徑,起始角,以弧度計,結(jié)束角咏雌,以弧度計默勾∑⊙剩可選志鞍。規(guī)定應(yīng)該逆時針還是順時針繪圖。False = 順時針优幸,true = 逆時針
// ctx.arc(400,300,200,0,2*Math.PI)
ctx.beginPath();
ctx.arc(0,0,200,0,2*Math.PI)
ctx.strokeStyle="darkgrey";
ctx.lineWidth=10;
ctx.stroke();
ctx.closePath();
ctx.restore();
ctx.save();
// 繪制分鐘刻度
for(let j=0;j<60;j++){
ctx.rotate(Math.PI/30)
ctx.beginPath();
ctx.moveTo(180,0);
ctx.lineTo(190,0);
ctx.lineWidth = 2;
ctx.strokeStyle="orangered"
ctx.stroke()
ctx.closePath();
}
ctx.restore();
ctx.save();
// 繪制時鐘刻度
for(let i=0;i<12;i++){
ctx.rotate(Math.PI/6)
ctx.beginPath();
ctx.moveTo(180,0);
ctx.lineTo(200,0);
ctx.lineWidth = 10;
ctx.strokeStyle="darkgray"
ctx.stroke()
ctx.closePath();
}
ctx.restore();
ctx.save();
// 繪制時鐘刻度數(shù)字
for(let i=1;i<=12;i++){
ctx.rotate((Math.PI/6));
ctx.save();
ctx.beginPath();
ctx.translate(165,-4);
ctx.rotate(Math.PI/2-(Math.PI/6)*i);
ctx.strokeStyle="skyblue"
// ctx.strokeText((i,150,0)
ctx.fillText(i, 0, 0);
// ctx.stroke();
ctx.closePath();
ctx.restore();
}
ctx.restore();
ctx.save();
}
// 初始化時鐘
function initClock(){
ctx.clearRect(0,0,800,600);
ctx.save();
// 將畫布移動畫布中央
ctx.translate(400,300);
ctx.rotate(-Math.PI/2)
ctx.save();
initClockBasicInfo();
let time = getDatetime();
// 繪制秒針
scaleRender(Math.PI/30*time[2],-30,170,2,"coral");
// 繪制分針
scaleRender(Math.PI/30*time[1]+2*Math.PI/3600*time[2],-20,150,3,"darkblue");// 根據(jù)分針的時間進行旋轉(zhuǎn)
// 繪制時針
scaleRender(Math.PI/6*time[0]+2*Math.PI/(12*60)*time[1] + 2*Math.PI/(12*3600)*time[2],
-10,140,3,"darkslategray");// 根據(jù)時針的時間進行旋轉(zhuǎn)
//
ctx.beginPath();
ctx.arc(0,0,2,0,Math.PI*2);
ctx.strokeStyle="red";
ctx.fill();
ctx.stroke();
ctx.closePath();
ctx.restore();
ctx.rotate(Math.PI/2)
ctx.font="20px 微軟雅黑";
ctx.fillText(`${time[0]}:${time[1]}:${time[2]}`,-40,260);
ctx.restore();
}
initClock();
setInterval(function(){
initClock();
},1000);
</script>
</body>
</html>
演示地址
寫于:2022年1月8日
作者QQ:420318184
郵箱:fy@0fy0.com