- 使用canvas的画线工具在圆盘中不断的画线,同时需要清除掉上一次的画线,需要对canva的整个画布进行更新;
- 直接移动和旋转canvas的坐标轴,这样画线的长度就可以固定,且起点和终点的纵坐标始终为0;
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<head title="test" />
</head>
<body>
<div>
<canvas id="myCanvas" />
</div>
<div id = "showTimes"></div>
</body>
<style>
html,body{
padding: 0;
margin: 0;
}
#myCanvas {
}
#showTimes{
background-color: black;
font-size: 20px;
color: white;
width: 300px;
text-align: center;
}
</style>
<script>
let myCanvas = document.getElementById("myCanvas");
let ctx = myCanvas.getContext('2d');
myCanvas.width = 400;
myCanvas.height = 400;
pi = Math.PI;
let second = 0;
let minutes = 0;
let hours = 0;
function drawDial (){
ctx.clearRect(0,0,400,400);
ctx.save();
ctx.translate(150,150);
for(let i = 0; i < 60; i++){
ctx.save();
ctx.rotate(-pi/2 + i*pi/30)
ctx.beginPath()
ctx.moveTo(148, 0)
ctx.lineTo(135, 0)
ctx.strokeStyle = 'blue'
ctx.lineWidth = i % 5 ? 2 : 4
ctx.stroke()
ctx.closePath()
ctx.restore()
}
ctx.restore()
}
function calcPointerAngle () {
var sAngle = second*pi/30
this.drawPinter('black', 125, sAngle, 2)
second = second < 59 ? second += 1 : 0;
if(second == 0){
if(minutes < 59){
minutes += 1;
}else{
minutes = 0;
hours += 1;
}
}
}
function drawPinter (color, length, angle, width) {
ctx.save()
ctx.translate(150, 150)
ctx.rotate(-pi/2 + angle)
ctx.beginPath()
ctx.moveTo(0,0)
ctx.lineTo(length, 0)
ctx.strokeStyle = color
ctx.lineWidth = width
ctx.lineCap = 'round'
ctx.stroke()
ctx.closePath()
ctx.restore()
let recordPlace = document.getElementById('showTimes');
recordPlace.innerHTML = `${hours >= 10 ? hours: '0'+hours} : ${minutes >= 10 ? minutes: '0'+minutes} : ${ second >= 10 ? second : '0'+second }`;
}
setInterval(()=>{
drawDial ();
calcPointerAngle ();
},1000)
</script>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b084b18a487393b563467609720d4740.png)