运行效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
canvas {
background: rgba(0, 0, 0, .1);
}
</style>
</head>
<body>
<canvas id="myCanvas" width="500" height="500">
您的浏览器不支持canvas
</canvas>
<script>
/**
* 绘制时分秒针
* strokeType:时、分、秒针
* angle:旋转角度
* strokeColor: 描边颜色
* lineWidth:线条宽度
* lineY:终点y坐标(坐标越远,指针越长)
*/
function drawClockWise(ctx, strokeType, angle, strokeColor, lineWidth, lineY) {
ctx.save()
//移动坐标轴原点到(250,250),方便指针旋转
ctx.translate(250, 250)
ctx.rotate(strokeType * angle * Math.PI / 180)
ctx.beginPath()
ctx.moveTo(0, 0)
ctx.lineTo(0, lineY)
ctx.strokeStyle = strokeColor;
ctx.lineWidth = lineWidth;
ctx.lineCap = "round"
ctx.closePath()
ctx.stroke()
ctx.restore()
}
/**
* 绘制表盘刻度
* num:刻度数量
* angle:旋转角度(每隔多少角度显示一个刻度)
* strokeColor: 描边颜色
* lineWidth:线条宽度
* moveX:起点x坐标
* lineX:终点x坐标
*/
function drawDial(ctx, num, angle, strokeColor, lineWidth, moveX, lineX) {
for (let i = 0; i < num; i++) {
ctx.save()
ctx.translate(250, 250)
ctx.rotate(i * angle * Math.PI / 180)
ctx.beginPath()
ctx.moveTo(moveX, 0)
ctx.lineTo(lineX, 0)
ctx.strokeStyle = strokeColor
ctx.lineWidth = lineWidth
ctx.lineCap = "round"
ctx.closePath()
ctx.stroke()
ctx.restore()
}
}
//绘制钟表
function draw() {
const myCanvas = document.getElementById('myCanvas');
if (!myCanvas.getContext) return;
const ctx = myCanvas.getContext('2d');
const date = new Date()
const seconds = date.getSeconds()
const minutes = date.getMinutes();
const hours = date.getHours();
ctx.clearRect(0, 0, 500, 500)
//绘制表盘背景
ctx.save()
ctx.translate(250, 250)
ctx.beginPath();
ctx.arc(0, 0, 100, 0, Math.PI * 2, false);
ctx.fillStyle = "#fff";
ctx.fill();
ctx.restore()
//绘制表盘刻度
drawDial(ctx, 60, 6, 'rgba(0,0,0,.3)', 1, 85, 95)
drawDial(ctx, 12, 30, 'rgba(0,0,0,.7)', 3, 80, 95)
//绘制时分秒针
drawClockWise(ctx, hours, 30, 'rgba(0,0,0,1)', 4, -60)
drawClockWise(ctx, minutes, 6, 'rgba(0,0,0,.8)', 2.5, -70)
drawClockWise(ctx, seconds, 6, 'rgba(0,0,0,.5)', 2, -80)
}
draw()
setInterval(() => {
draw()
}, 1000)
</script>
</body>
</html>