<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas Clock</title>
<style>
canvas {
display: block;
margin: 0 auto;
background-color: #f0f0f0;
}
</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 ang = num * Math.PI / 6; // 每个数字间隔30度
ctx.rotate(ang);
ctx.translate(0, -radius * 0.85);
ctx.rotate(-ang);
ctx.fillText(num.toString(), 0, 0);
ctx.rotate(ang);
ctx.translate(0, radius * 0.85);
ctx.rotate(-ang);
}
}
// 绘制指针
function drawTime(ctx, radius) {
const now = new Date();
let hour = now.getHours();
let minute = now.getMinutes();
let second = now.getSeconds();
// 计算角度
hour = hour % 12;
hour = (hour * Math.PI / 6) + (minute * Math.PI / (6 * 60)) + (second * Math.PI / (360 * 60));
drawHand(ctx, hour, radius * 0.5, radius * 0.07);
minute = (minute * Math.PI / 30) + (second * Math.PI / (30 * 60));
drawHand(ctx, minute, radius * 0.8, radius * 0.07);
second = (second * Math.PI / 30);
drawHand(ctx, second, radius * 0.9, radius * 0.02, 'red');
}
// 绘制每个指针
function drawHand(ctx, pos, length, width, color = '#333') {
ctx.beginPath();
ctx.lineWidth = width;
ctx.lineCap = "round";
ctx.strokeStyle = color;
ctx.moveTo(0, 0);
ctx.rotate(pos);
ctx.lineTo(0, -length);
ctx.stroke();
ctx.rotate(-pos);
}
// 每秒更新一次时钟
setInterval(drawClock, 1000);
drawClock(); // 初始化时钟
</script>
</body>
</html>
09-26
441
04-29