Cadran de l' horloge en toile


Partie II - Dessiner un cadran d'horloge

L'horloge a besoin d'un cadran. Créez une fonction JavaScript pour dessiner un cadran d'horloge :

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


Code expliqué

Créez une fonction drawFace() pour dessiner le cadran de l'horloge :

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

function drawFace(ctx, radius) {
}

Dessinez le cercle blanc :

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

Créez un dégradé radial (95 % et 105 % du rayon d'origine de l'horloge) :

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

Créez 3 arrêts de couleur, correspondant aux bords intérieur, central et extérieur de l'arc :

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

Les arrêts de couleur créent un effet 3D.

Définissez le dégradé comme style de trait de l'objet dessin :

ctx.strokeStyle = grad;

Définissez la largeur de ligne de l'objet dessiné (10 % du rayon) :

ctx.lineWidth = radius * 0.1;

Dessinez le cercle :

ctx.stroke();

Dessinez le centre de l'horloge :

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