html部分
<canvas id="watch" width="500px" height="500px" style="margin: 20px 30%;"></canvas>
样式部分
*{
margin: 0;
padding: 0;
}
body{
background-color: rgb(145, 174, 228);
}
逻辑部分
<script>
let c = document.getElementById('watch').getContext('2d')
setInterval(function(){
drawclock()
},1000)
function drawclock(){
c.clearRect(0,0,500,500)
c.beginPath()
c.arc(250,250,150,0,Math.PI*2)
c.strokeStyle = 'yellow'
c.lineWidth = 5
c.stroke()
for(let i=0;i<12;i++){
c.save()
c.translate(250,250)
c.rotate(i*Math.PI/6)
c.beginPath()
c.moveTo(0,-150)
c.lineTo(0,-125)
c.lineWidth = 5
c.stroke()
c.restore()
}
for(let i=0;i<60;i++){
c.save()
c.translate(250,250)
c.rotate(i*Math.PI/30)
c.beginPath()
c.moveTo(0,-150)
c.lineTo(0,-140)
c.lineWidth = 3
c.stroke()
c.restore()
}
let now = new Date(),
hour = now.getHours(),
minute = now.getMinutes(),
second = now.getSeconds()
let hours = hour + minute/60
hours = hour>12?hour-12:hour
c.save()
c.translate(250,250)
c.rotate(hours*Math.PI/6)
c.beginPath()
c.moveTo(0,10)
c.lineTo(0,-100)
c.lineWidth = 5
c.lineCap = 'round'
c.stroke()
c.restore()
c.save()
c.translate(250,250)
c.rotate(minute*Math.PI/30)
c.beginPath()
c.moveTo(0,13)
c.lineTo(0,-110)
c.lineWidth = 5
c.lineCap = 'round'
c.stroke()
c.restore()
c.save()
c.translate(250,250)
c.rotate(second*Math.PI/30)
c.beginPath()
c.moveTo(0,18)
c.lineTo(0,-130)
c.lineWidth = 2
c.lineCap = 'round'
c.strokeStyle = 'green'
c.stroke()
c.restore()
c.beginPath()
c.arc(250,250,5,0,Math.PI*2)
c.lineWidth = 2
c.strokeStyle = 'black'
c.stroke()
c.fillStyle = 'white'
c.fill()
c.fillStyle = 'black'
c.font = '18px Arial'
c.textAlign = 'center'
c.fillText('I am a watch!', 250,200)
}
</script>