Canvas 時鐘數字
第二部分 - 繪制鐘面
時鐘需要鐘面。創建一個 JavaScript 函數來繪制鐘面:
JavaScript:
function drawClock() { drawFace(ctx, radius); } function drawFace(ctx, radius) { 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.beginPath(); ctx.arc(0, 0, radius, 0, 2 * Math.PI); ctx.fillStyle = 'white'; ctx.fill(); ctx.strokeStyle = grad; 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(); }
代碼解釋
創建一個 drawFace() 函數來繪制鐘面:
function drawClock() { drawFace(ctx, radius); } function drawFace(ctx, radius) { }
畫出白色圓圈:
ctx.beginPath(); ctx.arc(0, 0, radius, 0, 2 * Math.PI); ctx.fillStyle = 'white'; ctx.fill();
創建徑向漸變(原始時鐘半徑的 95% 和 105%):
grad = ctx.createRadialGradient(0, 0, radius * 0.95, 0, 0, radius * 1.05);
創建 3 個色標,分別對應圓弧的內邊緣、中邊緣和外邊緣:
grad.addColorStop(0, '#333'); grad.addColorStop(0.5, 'white'); grad.addColorStop(1, '#333');
提示:這三個色標可產生 3D 效果。
將漸變定義為繪圖對象的筆觸樣式:
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();