Numbers of Canvas Clock

Part Two - Draw the Clock Face

The clock needs a clock face. Create a JavaScript function to draw the clock face:

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

Try It Yourself

Code Explanation

Create a drawFace() function to draw the clock face:

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

Draw a white circle:

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

Create a radial gradient (95% and 105% of the original clock radius):

grad = ctx.createRadialGradient(0, 0, radius * 0.95, 0, 0, radius * 1.05);

Create 3 color stops, corresponding to the inner, middle, and outer edges of the arc:

grad.addColorStop(0, '#333');
grad.addColorStop(0.5, 'white');
grad.addColorStop(1, '#333');

Tip: These three color stops can produce a 3D effect.

Define the gradient as the stroke style of the drawing object:

ctx.strokeStyle = grad;

Define the line width of the drawing object (10% of the radius):

ctx.lineWidth = radius * 0.1;

Draw a circle:

ctx.stroke();

Draw the center of the clock:

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

See Also:

Complete Canvas Reference Manual of CodeW3C.com