时钟样式
代码如下:
<canvas id="canvas" width="600" height="600"></canvas>
<script>
var canvas = document.querySelector("#canvas")
var cxt = canvas.getContext('2d')
function renderClock(){
cxt.clearRect(0,0,600,600)
cxt.save()
// 将中心坐标移到中点
cxt.translate(300,300)
cxt.rotate(-2*Math.PI/4)
// 绘制表盘
cxt.save()
cxt.beginPath()
cxt.arc(0,0,200,0,2*Math.PI)
cxt.strokeStyle = "hotpink"
cxt.lineWidth = 10
cxt.stroke()
cxt.closePath()
// 绘制秒刻度
for (let i = 0; i < 60; i++) {
cxt.rotate(Math.PI/30)
cxt.beginPath()
cxt.moveTo(190,0)
cxt.lineTo(200,0)
cxt.lineWidth = 2
cxt.stroke()
cxt.closePath()
}
// 绘制刻度
for (let i = 0; i < 12; i++) {
cxt.rotate(Math.PI/6)
cxt.beginPath()
cxt.moveTo(180,0)
cxt.lineTo(200,0)
cxt.lineWidth = 10
cxt.stroke()
cxt.closePath()
}
// 绘制刻度盘数字
cxt.restore()
cxt.save()
for (let i = 0; i < 12; i++) {
cxt.beginPath()
cxt.rotate(Math.PI/6)
cxt.font = "20px 微软雅黑";
cxt.fillText(i+1,155,7)
cxt.closePath()
}
cxt.restore()
cxt.save()
var time = new Date()
var hour = time.getHours()
var min = time.getMinutes()
var sec = time.getSeconds()
var hour = hour % 12
cxt.restore()
cxt.save()
// 绘制秒针
cxt.beginPath()
cxt.rotate(2*Math.PI/60*sec)
cxt.moveTo(-30,0)
cxt.lineTo(155,0)
cxt.strokeStyle = "blue"
cxt.lineWidth = 2
cxt.stroke()
cxt.closePath()
cxt.restore()
cxt.save()
// 绘制分针
cxt.beginPath()
cxt.rotate(2*Math.PI/60*min+2*Math.PI/3600*sec)
cxt.moveTo(-20,0)
cxt.lineTo(130,0)
cxt.strokeStyle = "green"
cxt.lineWidth = 3
cxt.stroke()
cxt.closePath()
cxt.restore()
cxt.save()
// 绘制时针
cxt.beginPath()
cxt.rotate(2*Math.PI/12*hour+2*Math.PI/60/12*min)
cxt.moveTo(-10,0)
cxt.lineTo(110,0)
cxt.strokeStyle = "red"
cxt.lineWidth = 4
cxt.stroke()
cxt.closePath()
// 中心小圆点
cxt.beginPath()
cxt.arc(0,0,5,0,2*Math.PI)
cxt.fillStyle = "yellow"
cxt.fill()
cxt.closePath()
cxt.restore()
cxt.restore()
}
setInterval(()=>{
renderClock()
},1000)
</script>