<!DOCTYPE html>
<html>
<head>
<title>时钟示例</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="200" height="200"></canvas>
<script>
// 获取 canvas 元素和其上下文
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// 获取画布中心点
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
// 绘制表盘
function drawClock() {
// 绘制表盘边框
ctx.beginPath();
ctx.arc(centerX, centerY, 80, 0, 2 * Math.PI);
ctx.strokeStyle = "black";
ctx.stroke();
// 绘制时钟数字
ctx.font = "15px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
for (var i = 1; i < 13; i++){
var angle = i * Math.PI / 6;
var x = centerX + Math.cos(angle) * 70;
var y = centerY + Math.sin(angle) * 70;
ctx.fillText(i.toString(), x, y);
}
// 绘制时钟中心点
ctx.beginPath();
ctx.arc(centerX, centerY, 2, 0, 2 * Math.PI);
ctx.fillStyle = "black";
ctx.fill();
}
// 绘制时钟指针
function drawHands(){
// 获取当前时间
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
// 绘制小时指针
ctx.beginPath();
ctx.lineWidth = 4;
ctx.lineCap = "round";
var angle = (hour % 12) * Math.PI / 6 + minute * Math.PI / 360;
var maxLength = 40;
var x = centerX + Math.cos(angle) * maxLength;
var y = centerY + Math.sin(angle) * maxLength;
ctx.moveTo(centerX, centerY);
ctx.lineTo(x, y);
ctx.strokeStyle = "black";
ctx.stroke();
// 绘制分钟指针
ctx.beginPath();
ctx.lineWidth = 2;
ctx.lineCap = "round";
angle = minute * Math.PI / 30 + second * Math.PI / 1800;
maxLength = 60;
x = centerX + Math.cos(angle) * maxLength;
y = centerY + Math.sin(angle) * maxLength;
ctx.moveTo(centerX, centerY);
ctx.lineTo(x, y);
ctx.strokeStyle = "black";
ctx.stroke();
// 绘制秒钟指针
ctx.beginPath();
ctx.lineWidth = 1;
ctx.lineCap = "round";
angle = second * Math.PI / 30;
maxLength = 70;
x = centerX + Math.cos(angle) * maxLength;
y = centerY + Math.sin(angle) * maxLength;
ctx.moveTo(centerX, centerY);
ctx.lineTo(x, y);
ctx.strokeStyle = "#D0211C";
ctx.stroke();
}
// 清空画布和重新绘制时钟
function clearAndDraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawClock();
drawHands();
}
// 每秒更新时钟指针
setInterval(clearAndDraw, 1000);
// 初次加载时绘制时钟
clearAndDraw();
</script>
</body>
</html>