參考教程
效果圖:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<Style>
#timetext{
position: absolute;
top:10;
left:20;
}
#canvas{
width:450px;
height:600px;
}
</Style>
</head>
<body>
<p id="timetext"></p>
<canvas id="canvas" width="600" height="800"></canvas>
</body>
<script>
let canvas=document.getElementById('canvas');
let timetext=document.querySelector('#timetext');
//console.log(timer)
//console.log(canvas)
let cxt=canvas.getContext('2d');
//console.log(cxt)
cxt.translate(300,300);//初始移動軸
var timer;
var hour;
var min;
var sec;
function time_update(){
let date=new Date();
hour=date.getHours();
hour=hour>12?hour-12:hour;
min=date.getMinutes();
sec=date.getSeconds();
timetext.innerHTML=date.toTimeString().slice(0,8);
cxt.clearRect(-300,-300,800,600)//清除掉上次的渲染
//按照順序渲染
hour_();min_();sec_();
pan();
timer=window.requestAnimationFrame(time_update);
}
time_update();//啓動requestAnimationFrame(默認間隔約16.7毫秒,對於瀏覽器一般最順暢的間隔
//console.log(hour,min,sec)
//window.cancelAnimationFrame(timer)
function pan(){//錶盤
cxt.save();//旋轉之前
//繪製小刻度
for(let i=0;i<60;i++){
cxt.strokeStyle='#afafaf';
//if(i%5==4)cxt.strokeStyle='#8a8a8a';
cxt.rotate(Math.PI/30)
cxt.beginPath();
cxt.moveTo(185,0)
cxt.lineTo(190,0)
cxt.lineWidth=3
cxt.stroke();
cxt.closePath();
}
cxt.restore();//恢復旋轉之前,其實正好一圈沒影響
//繪製大刻度
cxt.save();//旋轉之前
for(let i=0;i<12;i++){
cxt.rotate(Math.PI/6)
cxt.beginPath();
cxt.moveTo(180,0)
cxt.lineTo(195,0)
cxt.lineWidth=6
cxt.strokeStyle='#8a8a8a';
cxt.stroke();
cxt.closePath();
}
cxt.restore();//恢復旋轉之前,其實正好一圈沒影響
//繪製外圓
cxt.beginPath()
cxt.arc(0,0,200,0,2*Math.PI)
cxt.strokeStyle='#8a8a8a'
cxt.lineWidth=10
cxt.stroke();
cxt.closePath();
//繪製中心點
cxt.beginPath()
cxt.arc(0,0,5,0,2*Math.PI)
cxt.strokeStyle='black'
cxt.lineWidth=5
cxt.stroke();
cxt.fillStyle='white'
cxt.fill();
cxt.closePath();
cxt.restore();
}
function sec_(){
cxt.save();
//繪製秒針
cxt.rotate(sec*Math.PI/30-Math.PI/2)
cxt.beginPath();
cxt.moveTo(-30,0)
cxt.lineTo(160,0)
cxt.lineWidth=3
cxt.strokeStyle='#6c6';
cxt.stroke();
cxt.closePath();
cxt.restore();
}
function min_(){
cxt.save();
//繪製分針
cxt.rotate(min*Math.PI/30-Math.PI/2+sec*Math.PI/1800)
cxt.beginPath();
cxt.moveTo(-20,0)
cxt.lineTo(130,0)
cxt.lineWidth=5
cxt.strokeStyle='#264';
cxt.stroke();
cxt.closePath();
cxt.restore();
}
function hour_(){
cxt.save();
//繪製時針
cxt.rotate(hour*Math.PI/6-Math.PI/2+min*Math.PI/360+sec*2*Math.PI/12/60/60)
cxt.beginPath();
cxt.moveTo(-10,0)
cxt.lineTo(100,0)
cxt.lineWidth=8
cxt.strokeStyle='#910';
cxt.stroke();
cxt.closePath();
cxt.restore();
}
</script>
</html>