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();