Ring clock

by sthag

HTML

<canvas id="clockCanvas" width="300" height="300"></canvas>

JavaScript

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

class ClockRings {
  constructor(canvas, options = {}) {
    this.ctx = canvas.getContext("2d");
    this.width = canvas.width;
    this.height = canvas.height;

    // Default options
    this.options = {
      centerX: this.width / 2,
      centerY: this.height / 2,
      baseRadius: 100,
      ringWidth: 20,
      rings: [
        {
          maxValue: 60, // seconds
          color: "#4CAF50",
          radiusOffset: 0,
        },
        {
          maxValue: 60, // minutes
          color: "#2196F3",
          radiusOffset: 30,
        },
        {
          maxValue: 12, // hours
          color: "#FF5722",
          radiusOffset: 60,
        },
      ],
      backgroundColor: "#e0e0e0",
    };

    // Merge provided options with defaults
    this.options = { ...this.options, ...options };
  }

  drawRing(radius, progress, ringWidth, backgroundColor, fillColor) {
    const { ctx, options } = this;
    const { centerX, centerY } = options;

    // Draw background ring
    ctx.beginPath();
    ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
    ctx.lineWidth = ringWidth;
    ctx.strokeStyle = backgroundColor;
    ctx.stroke();

    // Draw fill ring
    ctx.beginPath();
    ctx.arc(
      centerX,
      centerY,
      radius,
      -Math.PI / 2,
      -Math.PI / 2 + progress * Math.PI * 2,
    );
    ctx.lineWidth = ringWidth;
    ctx.strokeStyle = fillColor;
    ctx.stroke();
  }

  animate() {
    const updateRings = () => {
      // Clear canvas
      this.ctx.clearRect(0, 0, this.width, this.height);

      // Get current date and time components
      const now = new Date();
      const seconds = now.getSeconds();
      const minutes = now.getMinutes();
      const hours = now.getHours() % 12; // Convert to 12-hour format

      // Draw rings
      this.options.rings.forEach((ring,...