Canvas-Uhr

In den folgenden Kapiteln werden wir eine simulierte Uhr mit dem HTML-Canvas aufbauen.

Teil 1 - Erstellen Sie das Canvas

Eine Uhr benötigt einen HTML-Container. Erstellen Sie ein HTML-Canvas:

HTML-Code:

<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width="400" height="400" style="background-color:#333"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let radius = canvas.height / 2;
ctx.translate(radius, radius);
radius = radius * 0.90
drawClock();
function drawClock() {
  ctx.arc(0, 0, radius, 0, 2 * Math.PI);
  ctx.fillStyle = "weiß";
  ctx.fill();
ctx.fill();
</script>
</body>
</html>

Versuchen Sie es selbst

Codeerklärung

Fügen Sie das HTML <canvas>-Element Ihrer Seite hinzu:

<canvas id="canvas" width="400" height="400" style="background-color:#333"></canvas>

Erstellen Sie ein Canvas-Objekt (const canvas):

const canvas = document.getElementById("canvas");

Erstellen Sie einen 2D-Zeichnungsobjekt (const ctx) für das Canvas-Objekt:

const ctx = canvas.getContext("2d");

Verwenden Sie die Höhe des Canvas, um den Uhrenradius zu berechnen:

let radius = canvas.height / 2;

Hinweis

Verwenden Sie die Höhe des Canvas, um den Uhrenradius zu berechnen, damit die Uhr für alle Canvas-Größen geeignet ist.

Setzen Sie den (Zeichnungsobjekts-)Punkt (0,0) neu in den Mittelpunkt des Canvas:

ctx.translate(radius, radius);

Verringern Sie den Uhrenradius (bis 90%) und zeichnen Sie die Uhr im Canvas ein:

radius = radius * 0.90;

Erstellen Sie eine Funktion zum Zeichnen einer Uhr:

function drawClock() {
  ctx.arc(0, 0, radius, 0, 2 * Math.PI);
  ctx.fillStyle = "weiß";
  ctx.fill();
ctx.fill();

}

Weitere Informationen: