HTML5的canvas元素为网页提供了强大的图形绘制能力,通过JavaScript操作canvas的上下文对象,我们可以实现从简单图形到复杂动态效果的各种绘制需求,动态时钟就是其中非常典型的应用场景,同时也能很好地体现canvas的高级使用技巧。

canvas基础环境搭建
首先需要在HTML页面中创建canvas元素,并获取其2D绘制上下文,这是所有canvas绘制操作的基础。canvas元素本身只是一个容器,实际的绘制逻辑都需要通过JavaScript操作上下文完成。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>canvas动态时钟</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
#clockCanvas {
background-color: #fff;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
</style>
</head>
<body>
<canvas id="clockCanvas" width="400" height="400"></canvas>
<script src="clock.js"></script>
</body>
</html>
在JavaScript中获取上下文的代码如下,后续所有绘制操作都基于这个ctx对象:
// 获取canvas元素和2D上下文
const canvas = document.getElementById('clockCanvas');
const ctx = canvas.getContext('2d');
// 设置时钟中心坐标和半径
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = Math.min(centerX, centerY) * 0.8;
绘制静态时钟基础结构
静态时钟需要绘制表盘、刻度、数字三个基础部分,这里会用到canvas的路径绘制、文本绘制、圆弧绘制等基础API。
绘制表盘外圆
使用arc方法绘制圆形表盘,同时设置描边样式:
function drawClockFace() {
// 保存当前绘图状态
ctx.save();
// 设置描边样式
ctx.strokeStyle = '#333';
ctx.lineWidth = 4;
// 绘制外圆
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
ctx.stroke();
// 恢复绘图状态
ctx.restore();
}
绘制刻度与数字
小时刻度和分钟刻度的长度、宽度不同,数字需要围绕圆心均匀分布,这里需要用到坐标变换的高级技巧,避免手动计算每个刻度的坐标:
function drawTicksAndNumbers() {
ctx.save();
// 将坐标原点移动到时钟中心
ctx.translate(centerX, centerY);
// 绘制小时刻度
for (let i = 0; i < 12; i++) {
ctx.save();
// 旋转坐标系,每个小时旋转30度(360/12)
ctx.rotate(Math.PI / 6 * i);
ctx.strokeStyle = '#333';
ctx.lineWidth = 3;
ctx.beginPath();
// 小时刻度从半径0.85位置到0.9位置
ctx.moveTo(0, -radius * 0.85);
ctx.lineTo(0, -radius * 0.9);
ctx.stroke();
ctx.restore();
}
// 绘制分钟刻度
for (let i = 0; i < 60; i++) {
// 跳过小时刻度的位置
if (i % 5 !== 0) {
ctx.save();
ctx.rotate(Math.PI / 30 * i);
ctx.strokeStyle = '#666';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(0, -radius * 0.87);
ctx.lineTo(0, -radius * 0.9);
ctx.stroke();
ctx.restore();
}
}
// 绘制小时数字
ctx.font = `${radius * 0.15}px Arial`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = '#333';
for (let i = 1; i <= 12; i++) {
ctx.save();
ctx.rotate(Math.PI / 6 * i);
// 数字绘制在半径0.7的位置
ctx.fillText(i, 0, -radius * 0.7);
ctx.restore();
}
ctx.restore();
}
绘制动态时钟指针
动态时钟的核心是获取当前时间,根据时、分、秒的数值计算指针的旋转角度,然后绘制对应的指针,这里需要注意指针的样式和旋转逻辑。
function drawHands() {
const now = new Date();
const hours = now.getHours() % 12;
const minutes = now.getMinutes();
const seconds = now.getSeconds();
// 计算各指针的旋转角度(弧度)
const secondAngle = Math.PI * 2 * seconds / 60;
const minuteAngle = Math.PI * 2 * (minutes + seconds / 60) / 60;
const hourAngle = Math.PI * 2 * (hours + minutes / 60) / 12;
ctx.save();
ctx.translate(centerX, centerY);
// 绘制时针
ctx.save();
ctx.rotate(hourAngle);
ctx.strokeStyle = '#333';
ctx.lineWidth = 6;
ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(0, radius * 0.1);
ctx.lineTo(0, -radius * 0.5);
ctx.stroke();
ctx.restore();
// 绘制分针
ctx.save();
ctx.rotate(minuteAngle);
ctx.strokeStyle = '#333';
ctx.lineWidth = 4;
ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(0, radius * 0.15);
ctx.lineTo(0, -radius * 0.7);
ctx.stroke();
ctx.restore();
// 绘制秒针
ctx.save();
ctx.rotate(secondAngle);
ctx.strokeStyle = '#f00';
ctx.lineWidth = 2;
ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(0, radius * 0.2);
ctx.lineTo(0, -radius * 0.8);
ctx.stroke();
// 绘制秒针中心的圆点
ctx.fillStyle = '#f00';
ctx.beginPath();
ctx.arc(0, 0, 5, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
ctx.restore();
}
实现动态更新效果
使用requestAnimationFrame实现动画循环,每一帧先清空画布,再重新绘制所有元素,就能实现时钟的动态更新效果,这个API比setInterval更适合动画场景,能匹配浏览器的刷新频率。
function updateClock() {
// 清空画布,使用透明填充避免残影
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 依次绘制各个部分
drawClockFace();
drawTicksAndNumbers();
drawHands();
// 请求下一帧更新
requestAnimationFrame(updateClock);
}
// 启动时钟更新
updateClock();
canvas高级技巧总结
在上面的动态时钟实现中,用到了多个canvas的高级使用技巧,这些技巧在更复杂的图形绘制场景中也非常实用:
- 绘图状态保存与恢复:通过
save()和restore()方法保存和恢复上下文的样式、变换状态,避免样式互相影响,减少重复设置的成本。 - 坐标变换:使用
translate()平移坐标系、rotate()旋转坐标系,可以简化围绕中心点的图形绘制逻辑,不需要手动计算每个点的坐标。 - 动画循环优化:使用
requestAnimationFrame代替定时器实现动画,能在浏览器标签页不活跃时自动暂停,减少性能消耗,同时动画更流畅。 - 路径管理:每个独立的图形绘制前使用
beginPath()开启新路径,避免不同图形的路径互相连接,保证绘制效果正确。
掌握这些技巧后,你可以尝试扩展这个时钟效果,比如添加背景渐变、指针阴影、数字时钟显示等功能,进一步熟悉canvas的图形绘制能力。