使用微信小程序制作时钟

<view class="container">
  <canvas canvas-id="clock" style="width: 300px; height: 300px;"></canvas>
</view>
Page({
  onReady() {
    const ctx = wx.createCanvasContext('clock');
    const width = 300;
    const height = 300;
    const radius = width / 2;

    function drawClock() {
      // 清除画布
      ctx.clearRect(0, 0, width, height);

      // 绘制表盘
      ctx.beginPath();
      ctx.arc(radius, radius, radius - 10, 0, 2 * Math.PI);
      ctx.setStrokeStyle('#333');
      ctx.setLineWidth(10);
      ctx.stroke();
      ctx.closePath();

      // 绘制时钟数字
      ctx.setFontSize(24);
      ctx.setTextAlign('center');
      ctx.setTextBaseline('middle');
      for (let i = 1; i <= 12; i++) {
        const angle = (i * 30 * Math.PI) / 180;
        const x = radius + (radius - 30) * Math.sin(angle);
        const y = radius - (radius - 30) * Math.cos(angle);
        ctx.fillText(i.toString(), x, y);
      }

      // 获取当前时间
      const now = new Date();
      const hours = now.getHours();
      const minutes = now.getMinutes();
      const seconds = now.getSeconds();

      // 绘制时针
      const hourAngle = ((hours % 12) * 30 + minutes / 2) * (Math.PI / 180);
      drawHand(ctx, hourAngle, radius * 0.5, 8);

      // 绘制分针
      const minuteAngle = (minutes * 6 + seconds / 10) * (Math.PI / 180);
      drawHand(ctx, minuteAngle, radius * 0.7, 5);

      // 绘制秒针
      const secondAngle = seconds * 6 * (Math.PI / 180);
      drawHand(ctx, secondAngle, radius * 0.9, 2);

      // 绘制中心圆点
      ctx.beginPath();
      ctx.arc(radius, radius, 5, 0, 2 * Math.PI);
      ctx.setFillStyle('#333');
      ctx.fill();
      ctx.closePath();

      // 绘制指针
      ctx.draw();
    }

    // 绘制指针
    function drawHand(ctx, angle, length, width) {
      ctx.beginPath();
      ctx.moveTo(radius, radius);
      ctx.lineTo(
        radius + length * Math.sin(angle),
        radius - length * Math.cos(angle)
      );
      ctx.setStrokeStyle('#333');
      ctx.setLineWidth(width);
      ctx.stroke();
      ctx.closePath();
    }

    // 刷新时钟
    setInterval(drawClock, 1000);
    drawClock(); // 初始化时钟
  }
});

在这里插入图片描述

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值