Canvas 時計の数字

第2部 - 钟面の描画

時計には钟面が必要です。钟面を描画する 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();

参照してください:

CodeW3C.comの完全なCanvasリファレンスマニュアル