Canvas 的強項在於把繪圖能力完全交給程式碼。以下用一個時鐘當作練習題,順便熟悉 save/restore、座標變換與旋轉這幾個最常用的手法。
做法是把畫布原點搬到中心,然後「畫一個指針朝右」當作模板,每次透過程式計算角度並旋轉座標系來重複使用同一組繪圖指令。時、分、秒刻度與指針都套用這個模式,只是旋轉角度與線寬不同。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>HTML5 Canvas 時鐘</title>
</head>
<body onload="init();">
<canvas id="myCanvas" width="300" height="300">
您的瀏覽器不支援 canvas 元素,請改用較新的瀏覽器。
</canvas>
</body>
</html>
標籤之間的文字是為不支援 Canvas 的環境準備的退路,這是 HTML5 一貫的「平穩退化」思路。
function init() {
clock();
setInterval(clock, 1000);
}
function clock() {
var now = new Date();
var ctx = document.getElementById('myCanvas').getContext('2d');
ctx.save();
ctx.clearRect(0, 0, 150, 150);
ctx.translate(75, 75); // 原點移到中心
ctx.scale(0.4, 0.4); // 整體縮放
ctx.rotate(-Math.PI / 2);// 讓 12 點方向朝上
ctx.strokeStyle = "black";
ctx.fillStyle = "white";
ctx.lineWidth = 8;
ctx.lineCap = "round";
// 時刻度
ctx.save();
for (var i = 0; i < 12; i++) {
ctx.beginPath();
ctx.rotate(Math.PI / 6);
ctx.moveTo(100, 0);
ctx.lineTo(120, 0);
ctx.stroke();
}
ctx.restore();
// 分刻度
ctx.save();
ctx.lineWidth = 5;
for (i = 0; i < 60; i++) {
if (i % 5 != 0) {
ctx.beginPath();
ctx.moveTo(117, 0);
ctx.lineTo(120, 0);
ctx.stroke();
}
ctx.rotate(Math.PI / 30);
}
ctx.restore();
var sec = now.getSeconds();
var min = now.getMinutes();
var hr = now.getHours();
hr = hr >= 12 ? hr - 12 : hr;
ctx.fillStyle = "black";
// 時針
ctx.save();
ctx.rotate(hr * (Math.PI / 6) + (Math.PI / 360) * min + (Math.PI / 21600) * sec);
ctx.lineWidth = 14;
ctx.beginPath();
ctx.moveTo(-20, 0);
ctx.lineTo(80, 0);
ctx.stroke();
ctx.restore();
// 分針
ctx.save();
ctx.rotate((Math.PI / 30) * min + (Math.PI / 1800) * sec);
ctx.lineWidth = 10;
ctx.beginPath();
ctx.moveTo(-28, 0);
ctx.lineTo(112, 0);
ctx.stroke();
ctx.restore();
// 秒針
ctx.save();
ctx.rotate(sec * Math.PI / 30);
ctx.strokeStyle = "#D40000";
ctx.fillStyle = "#D40000";
ctx.lineWidth = 6;
ctx.beginPath();
ctx.moveTo(-30, 0);
ctx.lineTo(83, 0);
ctx.stroke();
ctx.beginPath();
ctx.arc(0, 0, 10, 0, Math.PI * 2, true);
ctx.fill();
ctx.beginPath();
ctx.arc(95, 0, 10, 0, Math.PI * 2, true);
ctx.stroke();
ctx.fillStyle = "#555";
ctx.arc(0, 0, 3, 0, Math.PI * 2, true);
ctx.fill();
ctx.restore();
// 外框
ctx.beginPath();
ctx.lineWidth = 14;
ctx.strokeStyle = '#325FA2';
ctx.arc(0, 0, 142, 0, Math.PI * 2, true);
ctx.stroke();
ctx.restore();
}
save 與 restore 成對使用。每次改動 strokeStyle、lineWidth 或座標變換前先 save,畫完 restore,狀態才不會互相污染——這是整段程式能保持可讀的原因。
角度都用弧度。Math.PI / 6 就是 30 度,60 格分刻度則是 Math.PI / 30。Canvas 的 API 只吃弧度,習慣之後會比來回換算方便。
指針角度要考慮連續性。時針的角度除了小時,還疊加了分鐘與秒鐘的貢獻,這樣指針才會平滑前進而不是每小時跳一格。
把這段存成 HTML 檔開啟,如果用 Safari 或 Chrome 執行,你會看到一個每秒更新的類比時鐘。