Canvas 時計の面

❮ 前章へ 次章へ ❯

パート II - 時計の面を描画する

時計には時計の面が必要です。時計の面を描画する JavaScript 関数を作成します:

JavaScript:

function drawClock() {
    drawFace(ctx, radius);
}

function drawFace(ctx, radius) {
    var grad;

    ctx.beginPath();
    ctx.arc(0, 0, radius, 0, 2*Math.PI);
    ctx.fillStyle = 'white';
    ctx.fill();

    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.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();
}
Try it Yourself »

コードの説明

時計の面を描画するための 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();

❮ 前章へ 次章へ ❯