Skip to content

时钟表盘

为了构建我们的模拟时钟,第一个视觉组件是时钟表盘。我们将创建一个 JavaScript 函数来处理这个绘制工作。

drawFace 函数将渲染时钟的主要圆形主体、其边界以及中心点。

// 假设 'ctx' 是 2D 渲染上下文,'radius' 是期望的时钟半径。
function drawFace(ctx, radius) {
// 绘制表盘的主要白色圆圈
ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2 * Math.PI);
ctx.fillStyle = 'white';
ctx.fill();
// 为时钟外圈创建径向渐变(3D 效果)
// 渐变范围从半径稍内侧到半径稍外侧
const grad = ctx.createRadialGradient(0, 0, radius * 0.95, 0, 0, radius * 1.05);
grad.addColorStop(0, '#333'); // 外圈内侧颜色
grad.addColorStop(0.5, 'white'); // 外圈中间颜色(高光)
grad.addColorStop(1, '#333'); // 外圈外侧颜色
// 将渐变应用于描边样式
ctx.strokeStyle = grad;
// 设置外圈的线宽(半径的 10%)
ctx.lineWidth = radius * 0.1;
// 绘制外圈
ctx.stroke();
// 绘制时钟中心点
ctx.beginPath();
ctx.arc(0, 0, radius * 0.1, 0, 2 * Math.PI); // 中心点大小相对于半径
ctx.fillStyle = '#333';
ctx.fill();
}
// 示例用法(通常是更大时钟绘制函数的一部分):
// const canvas = document.getElementById('myClockCanvas');
// const ctx = canvas.getContext('2d');
// const radius = canvas.height / 2;
// ctx.translate(radius, radius); // 将原点移动到 canvas 中心
// const clockRadius = radius * 0.90; // 实际时钟半径,略小于 canvas 半径
// function drawClock() {
// drawFace(ctx, clockRadius);
// // 稍后,我们将添加 drawNumbers() 和 drawTime()
// }
// drawClock();
  1. drawFace(ctx, radius) 函数:

此函数封装了时钟表盘的所有绘图逻辑。它接收渲染上下文 (ctx) 和时钟的 radius 作为参数。

  1. 绘制白色圆圈(背景):
`ctx.beginPath();` 开始一条新的绘图路径。
`ctx.arc(0, 0, radius, 0, 2 * Math.PI);` 定义一个完整的圆,以 (0,0) 为中心(假设上下文已平移到时钟中心),半径为给定的 `radius`。
`ctx.fillStyle = 'white';` 设置填充颜色为白色。
`ctx.fill();` 填充圆。
  1. 创建径向渐变(外圈效果):
`const grad = ctx.createRadialGradient(0, 0, radius * 0.95, 0, 0, radius * 1.05);` 创建一个渐变。坐标 (0,0) 表示渐变与时钟表盘同心。它从半径的 95% 过渡到半径的 105%,创建出边界效果。
  1. 为渐变添加颜色停止点(addColorStop):
`grad.addColorStop(0, '#333');`
`grad.addColorStop(0.5, 'white');`
`grad.addColorStop(1, '#333');`
这些颜色停止点为外圈创建了类似 3D 的效果,中间有高光。
  1. 应用渐变并绘制外圈:
`ctx.strokeStyle = grad;` 将渐变设置为描边颜色。
`ctx.lineWidth = radius * 0.1;` 定义外圈的厚度(时钟半径的 10%)。
`ctx.stroke();` 使用渐变和线宽绘制圆形路径(外圈)。
  1. 绘制时钟中心点:
`ctx.beginPath();`
`ctx.arc(0, 0, radius * 0.1, 0, 2 * Math.PI);` 在中心定义一个小圆。
`ctx.fillStyle = '#333';` 设置其颜色。
`ctx.fill();` 填充中心点。

注意:在 drawFace 中使用的坐标(例如,圆弧中心的 0,0)假设 canvas 上下文已经被平移,使得 (0,0) 成为期望的时钟中心。这是简化绘图计算的常见做法。