简单html页面可以使用Live Preview插件预览,简介:Visual Studio Code实时预览插件live preview的安装和使用_yin_CSDN_1007的博客-CSDN博客
首先加入canvas元素
<canvas id="clock" width="400" height="400"></canvas>
js如下
const ctx = document.getElementById('clock').getContext('2d')
const cWidth = ctx.canvas.width, cHeight = ctx.canvas.height;
const r = Math.min(cWidth, cHeight) / 2 // 半径为canvas宽高中较小值的一半
function animate(time) {
const now = new Date()
const sec = now.getSeconds(), min = now.getMinutes(),
// h = now.getHours() < 12 ? now.getHours() : now.getHours() - 12;
h = now.getHours() % 12;
ctx.save()
ctx.clearRect(0, 0, cWidth, cHeight) // 每秒先清空画布
ctx.translate(cWidth / 2, cHeight / 2) // 将原点从左上角移到中间
ctx.rotate(-Math.PI / 2) // PI是180度,将水平的x轴逆时针旋转90度,和时钟一致从最12点开始,不旋转则会从3点开始
ctx.strokeStyle = 'black'
ctx.lineWidth = r / 32
ctx.lineCap = 'round'
ctx.save()
// 小时刻度
for(let i = 0; i < 12; i++) {
ctx.beginPath()
ctx.rotate(Math.PI / 6) // PI为180度,时针旋转半圈是6个小时,所以除以6。一圈360度12小时,一小时30度
ctx.moveTo(r/10*7, 0)
ctx.lineTo(r/10*9, 0)
ctx.stroke()
}
ctx.restore()
ctx.save()
// 分钟刻度
ctx.lineWidth = r / 50
for(let i = 0; i < 60; i++) {
ctx.beginPath()
ctx.rotate(Math.PI / 30) // 分针走180度为30分钟
ctx.moveTo(r/10*8, 0)
ctx.lineTo(r/10*9, 0)
ctx.stroke()
}
ctx.restore()
ctx.save()
// 每秒时针旋转的度数:时*每小时30度+分*每分钟30÷60度+秒*30÷60÷60度
ctx.rotate(
h * Math.PI / 6 + min * Math.PI / (6 * 60) + sec * Math.PI / (6 * 60 * 60)
)
ctx.lineWidth = r / 15
ctx.beginPath()
ctx.moveTo(-r / 8, 0)
ctx.lineTo(r/10*5.5, 0)
ctx.stroke()
ctx.restore()
ctx.save()
// 分针每秒旋转度数:分*180÷30度+秒*6÷60度
ctx.rotate(
min * Math.PI / 30 + sec * Math.PI / (30 * 60)
)
ctx.lineWidth = r / 20
ctx.beginPath()
ctx.moveTo(-r / 5, 0)
ctx.lineTo(r / 10*6.5, 0)
ctx.stroke()
ctx.restore()
ctx.save()
// 秒针每秒旋转度数
ctx.rotate(
sec * Math.PI / 30
)
ctx.strokeStyle = "red"
ctx.lineWidth = r / 40
ctx.beginPath()
ctx.moveTo(-r/10*2, 0)
ctx.lineTo(r*0.75, 0)
ctx.stroke()
ctx.arc(0, 0, r / 20, 0, 2 * Math.PI) // 红色小圆心,参数:圆心x坐标、圆心y坐标,半径,圆弧开始角度,圆弧结束角度
ctx.fillStyle = 'red'
ctx.fill()
ctx.restore()
ctx.restore()
window.requestAnimationFrame(animate)
}
window.requestAnimationFrame(animate)
关于requestAnimationFrame看这篇:requestAnimationFrame,读懂这篇文章就够了_前端同学的博客-CSDN博客
效果如图
如何优化
从上面代码可以看出每次都要清空整个画布,但是表的刻度其实是不变的,变化的是3个针。可以用两张画布,一张刻度下在,一张指针在上背景透明即可。
优化后续有空再更新