调用了window.requestAnimationFrame(绘制函数),然后在绘制函数中继续调用 window.requestAnimationFrame(绘制函数),这种情况下,每一次绘制都不能影响下一次,故需要在变换开始和结束的时候添加 ctx.save()/ctx.restore()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
<link rel="stylesheet" href="">
</head>
<body>
<canvas width="200" height="200" style="border: 1px solid #000"></canvas>
<script>
const ctx = document.querySelector('canvas').getContext('2d')
function draw() {
let time = new Date()
let h = time.getHours()
h = h>12?h-12:h
let m = time.getMinutes()
let s = time.getSeconds()
ctx.save()
ctx.clearRect(0, 0, 200, 200)
ctx.scale(0.5, 0.5)
ctx.translate(200, 200)
// 绘制直线等都是水平绘制的,反向旋转90度,正好同时间统一起来
ctx.rotate(-Math.PI/2)
// set gloabal ctx styles
ctx.fillStyle = '#fff'
ctx.strokeStyle = '#000'
ctx.lineWidth = 8
ctx.lineCap = 'round'
// draw hour marks,12个刻度,每隔2*Math.PI/12
ctx.save()
for(let i=0;i<12;i++){
ctx.beginPath()
ctx.moveTo(160,0)
ctx.lineTo(175,0)
ctx.stroke()
ctx.rotate(Math.PI/6)
}
ctx.restore()
// draw minute marks,一共60个刻度,碰到5的倍数就省略不画,每隔2*Math.PI/(12*5)
ctx.save()
ctx.lineWidth = 5
for (let i = 0; i < 60; i++) {
if(i%5!==0){
ctx.beginPath()
ctx.moveTo(164, 0)
ctx.lineTo(170, 0)
ctx.stroke()
}
ctx.rotate(Math.PI / 30)
}
ctx.restore()
// NUMBER
ctx.save()
ctx.fillStyle = "#000"
ctx.font = "30px verdana"
ctx.rotate(Math.PI / 2)
for (let i = 1; i <= 12; i++) {
// 半径为圆盘的半径 - 20
let x = 140 * Math.sin(i * Math.PI / 6)
let y = -140 * Math.cos(i * Math.PI / 6)
ctx.fillText(i, x - 10, y + 9)
}
ctx.restore()
//draw hour
ctx.save()
ctx.lineWidth = 12
ctx.rotate(h*Math.PI/6+m*Math.PI/360+s*Math.PI/21600)
ctx.beginPath()
ctx.moveTo(-15,0)
ctx.lineTo(105,0)
ctx.stroke()
ctx.restore()
//draw minute
ctx.save()
ctx.lineWidth = 6
ctx.rotate( m *2* Math.PI / 60 + s *2* Math.PI / (60*60))
ctx.beginPath()
ctx.moveTo(-20, 0)
ctx.lineTo(126, 0)
ctx.stroke()
ctx.restore()
// draw seconds
ctx.save()
ctx.lineWidth = 3
ctx.rotate(s*Math.PI/30)
ctx.strokeStyle = "#f00"
ctx.beginPath()
ctx.moveTo(-25,0)
ctx.lineTo(110,0)
ctx.stroke()
ctx.beginPath()
ctx.fillStyle = "red"
ctx.arc(0, 0, 10,0, 2 * Math.PI, true)
ctx.fill()
ctx.beginPath()
ctx.arc(120,0, 10, 0, 2*Math.PI, true)
ctx.stroke()
ctx.restore()
// drwa clock circle
ctx.save()
ctx.strokeStyle = "#325fa2"
ctx.beginPath()
ctx.arc(0,0, 180, 0, 2*Math.PI, true)
ctx.stroke()
ctx.restore()
ctx.restore()
window.requestAnimationFrame(draw)
}
window.requestAnimationFrame(draw)
</script>
</body>
</html>