Canvas-Uhr-Ziffern

Teil 2 - Zeichnen Sie die Uhrzeigerfläche

Die Uhr benötigt eine Uhrzeigerfläche. Erstellen Sie eine JavaScript-Funktion zur Zeichnung der Uhrzeigerfläche:

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

Probieren Sie es selbst aus

Codeerklärung

Erstellen Sie eine Funktion drawFace() zur Zeichnung der Uhrzeiger:

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

Zeichnen Sie einen weißen Kreis:

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

Erstellen Sie einen radialen Farbverlauf (95% und 105% des ursprünglichen Uhrenradius):

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

Erstellen Sie 3 Farbmarken, die den Innenrand, den Mittelrand und den Außenrand des Bogenkreises entsprechen:

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

Hinweis: Diese drei Farbmarken erzeugen einen 3D-Effekt.

Definieren Sie die Farbverlaufsstil des Zeichenobjekts als Farbverlauf:

ctx.strokeStyle = grad;

Definieren Sie die Linienbreite des Zeichenobjekts (10% des Radius):

ctx.lineWidth = radius * 0.1;

Zeichnen Sie einen Kreis:

ctx.stroke();

Zeichnen Sie den Mittelpunkt der Uhr:

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

Weitere Informationen siehe:

Vollständiges Canvas-Referenzhandbuch von CodeW3C.com