
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas 时钟</title>
<style>
canvas {
display: block;
margin: 50px auto;
background-color: #f0f0f0;
border: 2px solid #333;
border-radius: 50%;
}
</style>
</head>
<body>
<canvas id="clockCanvas" width="400" height="400"></canvas>
<script >
const canvas = document.getElementById("clockCanvas");
const ctx = canvas.getContext("2d");
const radius = canvas.width / 2;
// 将绘图原点移至中心
ctx.translate(radius, radius);
// 时钟半径
const clockRadius = radius * 0.9;
function drawClock() {
drawFace(ctx, clockRadius);
drawNumbers(ctx, clockRadius);
drawTime(ctx, clockRadius);
}
// 绘制钟表表盘
function drawFace(ctx, radius) {
ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2 * Math.PI);
ctx.fillStyle = "white";
ctx.fill();
ctx.strokeStyle = "#333";
ctx.lineWidth = radius * 0.05;
ctx.stroke();
ctx.beginPath();
ctx.arc(0, 0, radius * 0.1, 0, 2 * Math.PI);
ctx.fillStyle = "#333";
ctx.fill();
}
// 绘制数字
function drawNumbers(ctx, radius) {
ctx.font = `${radius * 0.15}px Arial`;
ctx.textBaseline = "middle";
ctx.textAlign = "center";
for (let num = 1; num <= 12; num++) {
const angle = (num * Math.PI) / 6;
const x = radius * 0.85 * Math.cos(angle);
const y = radius * 0.85 * Math.sin(angle);
ctx.fillText(num.toString(), x, y);
}
}
// 绘制时针、分针和秒针
function drawTime(ctx, radius) {
const now = new Date();
const hour = now.getHours();
const minute = now.getMinutes();
const second = now.getSeconds();
// 时针
const hourAngle =
((hour % 12) * Math.PI) / 6 +
(minute * Math.PI) / (6 * 60) +
(second * Math.PI) / (360 * 60);
drawHand(ctx, hourAngle, radius * 0.5, radius * 0.07);
// 分针
const minuteAngle = (minute * Math.PI) / 30 + (second * Math.PI) / (30 * 60);
drawHand(ctx, minuteAngle, radius * 0.8, radius * 0.05);
// 秒针
const secondAngle = (second * Math.PI) / 30;
drawHand(ctx, secondAngle, radius * 0.9, radius * 0.02, "red");
}
// 绘制指针
function drawHand(ctx, angle, length, width, color = "#333") {
ctx.beginPath();
ctx.lineWidth = width;
ctx.lineCap = "round";
ctx.strokeStyle = color;
ctx.moveTo(0, 0);
ctx.rotate(angle);
ctx.lineTo(0, -length);
ctx.stroke();
ctx.rotate(-angle);
}
// 每秒更新时钟
setInterval(drawClock, 1000);
// 初始化时钟
drawClock();
</script>
</body>
</html>