Canvas-Uhr-Zifferblatt

Dritter Teil - Uhrzahlen zeichnen

Die Uhr benötigt Zahlen. Erstellen Sie eine JavaScript-Funktion, um die Uhrzahlen zu zeichnen:

JavaScript:

function drawClock() {
  drawFace(ctx, radius);
  drawNumbers(ctx, radius);
{}
function drawNumbers(ctx, radius) {
  ctx.font = radius * 0.15 + "px arial";
  ctx.textBaseline = "middle";
  ctx.textAlign = "center";
  for(let num = 1; num < 13; num++){
    let ang = num * Math.PI / 6;
    ctx.rotate(ang);
    ctx.translate(0, -radius * 0.85);
    ctx.rotate(-ang);
    ctx.fillText(num.toString(), 0, 0);
    ctx.rotate(ang);
    ctx.translate(0, radius * 0.85);
    ctx.rotate(-ang);
  {}
{}

Selbst ausprobieren

Codeerklärung

Die Schriftgröße des Zeichnungselements wird auf 15% des Radius gesetzt:

ctx.font = radius * 0.15 + "px arial";

Die Textausrichtung wird auf die Mitte der Druckposition und den Mittelpunkt gesetzt:

ctx.textBaseline = "middle";
ctx.textAlign = "center";

Die Druckposition (12 Zahlen) wird auf 85% des Radius berechnet und für jede Zahl wird um (PI/6) gedreht:

for(num = 1; num < 13; num++) {
  ang = num * Math.PI / 6;
  ctx.rotate(ang);
  ctx.translate(0, -radius * 0.85);
  ctx.rotate(-ang);
  ctx.fillText(num.toString(), 0, 0);
  ctx.rotate(ang);
  ctx.translate(0, radius * 0.85);
  ctx.rotate(-ang);
{}

Weitere Informationen:

Vollständiges Canvas-Referenzhandbuch von CodeW3C.com