使用svg 实现一个可视化时钟

34 阅读1分钟

image.png

复制代码即可运行

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>SVG Clock</title>
  <style>
    svg {
      width: 400px;
      height: 400px;
    }

    .hour-mark {
      stroke: black;
      stroke-width: 3;
    }

    .clock-number {
      font-size: 24px;
      text-anchor: middle;
      alignment-baseline: middle;
    }
  </style>
</head>

<body>
  <svg viewBox="0 0 400 400">
    <!-- 表盘 -->
    <circle cx="200" cy="200" r="190" stroke="black" stroke-width="4" fill="white" />
    <!-- 刻度和数字 -->
    <g>
      <!-- 使用循环生成刻度和数字 -->
    </g>
    <!-- 时针 -->
    <line id="hour" x1="200" y1="200" x2="200" y2="120" stroke="black" stroke-width="8" />
    <!-- 分针 -->
    <line id="minute" x1="200" y1="200" x2="200" y2="100" stroke="black" stroke-width="6" />
    <!-- 秒针 -->
    <line id="second" x1="200" y1="200" x2="200" y2="80" stroke="red" stroke-width="4" />
  </svg>
  <script>
    const svgNS = "http://www.w3.org/2000/svg";
    for (let i = 1; i <= 12; i++) {
      let angle = (i * 30) * (Math.PI / 180); // 将角度转换为弧度
      let x = 200 + Math.sin(angle) * 160;
      let y = 200 - Math.cos(angle) * 160;

      // 添加数字
      let text = document.createElementNS(svgNS, "text");
      text.setAttribute("x", x);
      text.setAttribute("y", y + 8); // 轻微调整以居中显示
      text.setAttribute("class", "clock-number");
      text.textContent = i.toString();
      document.querySelector("svg").appendChild(text);

      // 添加刻度
      let line = document.createElementNS(svgNS, "line");
      let x1 = 200 + Math.sin(angle) * 170;
      let y1 = 200 - Math.cos(angle) * 170;
      let x2 = 200 + Math.sin(angle) * 190;
      let y2 = 200 - Math.cos(angle) * 190;
      line.setAttribute("x1", x1);
      line.setAttribute("y1", y1);
      line.setAttribute("x2", x2);
      line.setAttribute("y2", y2);
      line.setAttribute("class", "hour-mark");
      document.querySelector("svg").appendChild(line);
    }
  </script>
  <script>
    function updateClock() {
      const now = new Date();
      const second = now.getSeconds();
      const minute = now.getMinutes();
      const hour = now.getHours();

      const secondAngle = second * 6; // 每秒6度
      const minuteAngle = (minute + second / 60) * 6; // 每分钟6度,加上秒针的影响
      const hourAngle = (hour % 12 + minute / 60 + second / 3600) * 30; // 每小时30度,加上分针和秒针的影响

      document.getElementById('hour').setAttribute('transform', `rotate(${hourAngle}, 200, 200)`);
      document.getElementById('minute').setAttribute('transform', `rotate(${minuteAngle}, 200, 200)`);
      document.getElementById('second').setAttribute('transform', `rotate(${secondAngle}, 200, 200)`);
    }

    // 每秒更新时钟
    setInterval(updateClock, 1000);

    // 初始化时钟
    updateClock();
  </script>
</body>

</html>