利用 Canvas 繪製模擬時鐘是練習動畫循環、三角函數應用、狀態保存恢復的經典案例。本文提供完整實現代碼,涵蓋表盤、刻度、指針繪製與定時器驅動,助你理解 Canvas 動畫核心模式。
drawFrame() 獲取當前時間 → 清空畫布 → 繪製表盤/刻度/指針setInterval(drawFrame, 1000) 或 requestAnimationFrame 持續更新<canvas id="clock" width="500" height="500" style="background: #ffff00"></canvas>
<script>
const canvas = document.getElementById('clock');
const ctx = canvas.getContext('2d');
const CX = 250, CY = 250, R = 200; // 中心點與半徑
function drawClock() {
ctx.clearRect(0, 0, 500, 500);
drawFace();
drawTicks();
drawHands();
}
function drawFace() {
ctx.save();
ctx.lineWidth = 10;
ctx.strokeStyle = 'blue';
ctx.beginPath();
ctx.arc(CX, CY, R, 0, Math.PI * 2);
ctx.stroke();
ctx.restore();
}
function drawTicks() {
// 時刻度:12 條,粗長
ctx.save();
ctx.lineWidth = 7;
ctx.strokeStyle = 'black';
for (let i = 0; i < 12; i++) {
const angle = i * Math.PI / 6; // 30°
ctx.beginPath();
ctx.moveTo(CX + Math.cos(angle) * (R - 30), CY + Math.sin(angle) * (R - 30));
ctx.lineTo(CX + Math.cos(angle) * (R - 10), CY + Math.sin(angle) * (R - 10));
ctx.stroke();
}
ctx.restore();
// 分刻度:60 條,細短
ctx.save();
ctx.lineWidth = 3;
for (let i = 0; i < 60; i++) {
if (i % 5 === 0) continue; // 跳過時刻度位置
const angle = i * Math.PI / 30; // 6°
ctx.beginPath();
ctx.moveTo(CX + Math.cos(angle) * (R - 20), CY + Math.sin(angle) * (R - 20));
ctx.lineTo(CX + Math.cos(angle) * (R - 10), CY + Math.sin(angle) * (R - 10));
ctx.stroke();
}
ctx.restore();
}
function drawHands() {
const now = new Date();
const h = (now.getHours() % 12) + now.getMinutes() / 60; // 時針需含分针偏移
const m = now.getMinutes() + now.getSeconds() / 60;
const s = now.getSeconds() + now.getMilliseconds() / 1000;
// 時針
drawHand(h * Math.PI / 6, 80, 7, 'black');
// 分针
drawHand(m * Math.PI / 30, 120, 5, 'black');
// 秒針
drawHand(s * Math.PI / 30, 140, 2, 'red');
// 中心圓點
ctx.beginPath();
ctx.arc(CX, CY, 6, 0, Math.PI * 2);
ctx.fillStyle = 'gray';
ctx.fill();
}
function drawHand(angle, length, width, color) {
ctx.save();
ctx.translate(CX, CY);
ctx.rotate(angle);
ctx.beginPath();
ctx.moveTo(0, 10); // 指針尾部稍後延
ctx.lineTo(0, -length);
ctx.lineWidth = width;
ctx.strokeStyle = color;
ctx.lineCap = 'round';
ctx.stroke();
ctx.restore();
}
// 啟動
drawClock();
setInterval(drawClock, 1000); // 或 requestAnimationFrame 循環
</script>
使用 translate(centerX, centerY) 將原點移至圓心,配合 rotate(angle) 旋轉畫布,指針繪製簡化為「從原點向上畫線」,無需手算三角函數端點坐標。
每個繪製單元(表盤、刻度、各指針)用 save()/restore() 包裹,確保變換、樣式不相互污染。
時針:hours + minutes/60
分针:minutes + seconds/60
秒針:seconds + ms/1000
實現指針連續平滑轉動而非跳躍。
requestAnimationFrame 替代 setInterval,對齊瀏覽器刷新率clearRect 僅清除指針區域(配合 globalCompositeOperation='destination-out')可進一步提升性能fillText + 三角函數定位)這個時鐘示例展示了 Canvas 動畫的標準模式:狀態隔離 + 變換矩陣 + 定時循環。掌握此模式,可輕鬆延展至儀表盤、數據可視化動畫、遊戲主循環等更複雜場景。