閒來無事做個時鐘來玩玩
用canvas 繪製時鐘的大圓,使用動畫讓指針按照對應的時間速度轉動
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<canvas id="canvas1" width="800" height="600"></canvas>
<!--
1:錶盤
2:刻度
3:指針
4:獲取時間
獲取時間,重新繪製:每隔1秒鐘繪製:
-->
<script type="text/javascript">
var canvas1 = document.querySelector('#canvas1')
var ctx = canvas1.getContext('2d')
function drawTime(){
//清盤
ctx.clearRect(0,0,800,600)
//錶盤
ctx.beginPath()
ctx.arc(400,300,200,0,2*Math.PI)
ctx.lineWidth = 10
ctx.strokeStyle = 'grey'
ctx.stroke()
ctx.closePath()
ctx.save()//保留這個座標系的位置,以及保留ctx的屬性樣式
//刻度
ctx.translate(400,300)
ctx.save()//保留了移動後的座標原點爲400,300像素位置的座標系
//分針的刻度
for(var i = 0; i< 60;i++){
ctx.beginPath()
//移動座標系
//有60個刻度,所以每一次旋轉360(2*Math.pi)/60
ctx.rotate(2*Math.PI/60)
ctx.moveTo(170,0)
ctx.lineTo(190,0)
ctx.lineWidth = 5
ctx.strokeStyle = '#aaa'
ctx.stroke()
ctx.closePath()
}
ctx.restore()//恢復到沒有旋轉前,恢復到座標系爲400,300像素位置的座標系
ctx.save()
//時鐘的刻度
for(var i = 0; i< 12;i++){
ctx.beginPath()
//移動座標系
//有60個刻度,所以每一次旋轉360(2*Math.pi)/60
ctx.rotate(2*Math.PI/12)
ctx.moveTo(165,0)
ctx.lineTo(190,0)
ctx.lineWidth = 10
ctx.strokeStyle = '#333'
ctx.stroke()
ctx.closePath()
}
ctx.restore()
ctx.save()
//獲取時間
var nowTime = new Date()
//獲取小時
var hour = nowTime.getHours()
//獲取分
var min = nowTime.getMinutes()
//獲取秒
var sec = nowTime.getSeconds()
if(hour>=12){
hour = hour-12
}
console.log(hour,min,sec)
//將座標系逆時針旋轉90
ctx.rotate(-2*Math.PI/4)
ctx.save()
//首先繪製秒針
ctx.beginPath()
ctx.rotate(2*Math.PI/60*sec)
ctx.moveTo(-20,0)
ctx.lineTo(150,0)
ctx.lineWidth = 3
ctx.strokeStyle = 'red'
ctx.stroke()
ctx.closePath()
ctx.restore()
ctx.save()
//繪製分針
ctx.beginPath()
ctx.rotate(2*Math.PI/60*min + 2*Math.PI/60*sec/60)
ctx.moveTo(-15,0)
ctx.lineTo(140,0)
ctx.lineWidth = 5
ctx.strokeStyle = 'darkslategray'
ctx.stroke()
ctx.closePath()
ctx.restore()
ctx.save()
//繪製時針
ctx.beginPath()
ctx.rotate(2*Math.PI/12*hour+2*Math.PI/12*min/60+ 2*Math.PI/12/60*sec/60)
ctx.moveTo(-10,0)
ctx.lineTo(100,0)
ctx.lineWidth = 10
ctx.strokeStyle = 'darkslategray'
ctx.stroke()
ctx.closePath()
ctx.restore()
ctx.restore()
ctx.restore()
requestAnimationFrame(drawTime)
}
//盡最大能力去渲染,也可以保證不卡幀,請求動畫幀的方法。
requestAnimationFrame(drawTime)
</script>
</body>
</html>