引言
在前端开发中,HTML5的Canvas是一个非常强大的工具,它可以用来绘制各种图形、动画和交互效果。今天,我们将通过一个简单的案例,使用Canvas来实现一个动态的时钟动画。这个时钟不仅能够显示当前的时间,还能够实时更新,模拟真实的时钟效果。
实现思路
1. Canvas基础:我们使用Canvas的2D上下文来绘制时钟的各个部分,包括表盘、时针、分针、秒针以及中心圆点。
2. 时间获取:通过JavaScript的`Date`对象获取当前的时间,并将其转换为时针、分针和秒针的角度。
3. 动画效果:使用`requestAnimationFrame`来实现时钟的实时更新,确保每一秒都能重新绘制时钟。
代码解析
<!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>
</head>
<body>
<canvas id="canvas" width="600" height="600" style="border: 1px solid black"></canvas>
<script>
// 获取canvas节点和2D上下文
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
// 绘制时钟函数
function drawClock() {
ctx.save();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.translate(canvas.width / 2, canvas.height / 2);
// 设置画笔样式
ctx.strokeStyle = "black";
ctx.lineWidth = canvas.width * 0.025;
ctx.lineCap = "round";
let radius = (canvas.width / 2) * 0.9;
let date = new Date();
let hour = date.getHours() % 12;
let minute = date.getMinutes();
let second = date.getSeconds();
// 绘制时针刻度
ctx.save();
for (let i = 0; i < 12; i++) {
ctx.beginPath();
ctx.rotate((Math.PI * 2) / 12);
ctx.moveTo(0, -radius);
ctx.lineTo(0, -radius + 50);
ctx.stroke();
}
ctx.restore();
// 绘制分针刻度
ctx.save();
ctx.lineWidth = canvas.width * 0.015;
for (let i = 0; i < 60; i++) {
ctx.beginPath();
ctx.rotate((Math.PI * 2) / 60);
ctx.moveTo(0, -radius);
ctx.lineTo(0, -radius + 20);
ctx.stroke();
}
ctx.restore();
// 绘制时针
ctx.save();
ctx.rotate((hour * Math.PI) / 6 + (minute * Math.PI) / (6 * 60) + (second * Math.PI) / (360 * 60));
ctx.lineWidth = canvas.width * 0.05;
ctx.beginPath();
ctx.moveTo(0, 20);
ctx.lineTo(0, -radius * 0.6);
ctx.stroke();
ctx.restore();
// 绘制分针
ctx.save();
ctx.rotate((minute * Math.PI) / 30 + (second * Math.PI) / (30 * 60));
ctx.lineWidth = canvas.width * 0.03;
ctx.beginPath();
ctx.moveTo(0, 30);
ctx.lineTo(0, -radius * 0.7);
ctx.stroke();
ctx.restore();
// 绘制秒针
ctx.save();
ctx.rotate((second * Math.PI) / 30);
ctx.lineWidth = canvas.width * 0.018;
ctx.strokeStyle = "red";
ctx.beginPath();
ctx.moveTo(0, 45);
ctx.lineTo(0, -radius * 0.85);
ctx.stroke();
ctx.restore();
// 绘制中心圆点
ctx.save();
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(0, 0, 14, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
ctx.restore();
}
// 使用requestAnimationFrame实现动画
function animate() {
drawClock();
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
关键点解析
-
Canvas的坐标系:Canvas的坐标系原点在左上角,我们通过
ctx.translate将原点移动到画布中心,方便绘制时钟。 -
旋转角度计算:时针、分针和秒针的旋转角度通过当前时间计算得出,确保指针能够准确指向正确的时间。
1万+

被折叠的 条评论
为什么被折叠?



