canvas 自动钟表

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Canvas Clock</title>
  <style>
    canvas {
      display: block;
      margin: 0 auto;
      background-color: #f0f0f0;
    }
  </style>
</head>
<body>

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

  <script>
    const canvas = document.getElementById('clockCanvas');
    const ctx = canvas.getContext('2d');
    const radius = canvas.width / 2;
    ctx.translate(radius, radius); // 将坐标系移到画布中心
    const clockRadius = radius * 0.9;

    // 绘制时钟的主函数
    function drawClock() {
      drawFace(ctx, clockRadius); // 绘制钟表盘
      drawNumbers(ctx, clockRadius); // 绘制数字
      drawTime(ctx, clockRadius); // 绘制指针
    }

    // 绘制表盘
    function drawFace(ctx, radius) {
      ctx.beginPath();
      ctx.arc(0, 0, radius, 0, 2 * Math.PI);
      ctx.fillStyle = 'white';
      ctx.fill();

      ctx.strokeStyle = '#333';
      ctx.lineWidth = radius * 0.05;
      ctx.stroke();

      // 绘制中心圆点
      ctx.beginPath();
      ctx.arc(0, 0, radius * 0.1, 0, 2 * Math.PI);
      ctx.fillStyle = '#333';
      ctx.fill();
    }

    // 绘制表盘上的数字
    function drawNumbers(ctx, radius) {
      ctx.font = `${radius * 0.15}px Arial`;
      ctx.textBaseline = "middle";
      ctx.textAlign = "center";
      for (let num = 1; num <= 12; num++) {
        const ang = num * Math.PI / 6; // 每个数字间隔30度
        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);
      }
    }

    // 绘制指针
    function drawTime(ctx, radius) {
      const now = new Date();
      let hour = now.getHours();
      let minute = now.getMinutes();
      let second = now.getSeconds();

      // 计算角度
      hour = hour % 12;
      hour = (hour * Math.PI / 6) + (minute * Math.PI / (6 * 60)) + (second * Math.PI / (360 * 60));
      drawHand(ctx, hour, radius * 0.5, radius * 0.07);

      minute = (minute * Math.PI / 30) + (second * Math.PI / (30 * 60));
      drawHand(ctx, minute, radius * 0.8, radius * 0.07);

      second = (second * Math.PI / 30);
      drawHand(ctx, second, radius * 0.9, radius * 0.02, 'red');
    }

    // 绘制每个指针
    function drawHand(ctx, pos, length, width, color = '#333') {
      ctx.beginPath();
      ctx.lineWidth = width;
      ctx.lineCap = "round";
      ctx.strokeStyle = color;
      ctx.moveTo(0, 0);
      ctx.rotate(pos);
      ctx.lineTo(0, -length);
      ctx.stroke();
      ctx.rotate(-pos);
    }

    // 每秒更新一次时钟
    setInterval(drawClock, 1000);

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

</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值