用canvas绘制钟表动效

运行效果
在这里插入图片描述

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    canvas {
      background: rgba(0, 0, 0, .1);
    }
  </style>
</head>

<body>
  <canvas id="myCanvas" width="500" height="500">
    您的浏览器不支持canvas
  </canvas>

  <script>
    /**
     * 绘制时分秒针
     * strokeType:时、分、秒针
     * angle:旋转角度
     * strokeColor: 描边颜色
     * lineWidth:线条宽度
     * lineY:终点y坐标(坐标越远,指针越长)
    */
    function drawClockWise(ctx, strokeType, angle, strokeColor, lineWidth, lineY) {
      ctx.save()
      //移动坐标轴原点到(250,250),方便指针旋转
      ctx.translate(250, 250)
      ctx.rotate(strokeType * angle * Math.PI / 180)

      ctx.beginPath()
      ctx.moveTo(0, 0)
      ctx.lineTo(0, lineY)
      ctx.strokeStyle = strokeColor;
      ctx.lineWidth = lineWidth;
      ctx.lineCap = "round"
      ctx.closePath()
      ctx.stroke()
      ctx.restore()
    }

    /**
     * 绘制表盘刻度
     * num:刻度数量
     * angle:旋转角度(每隔多少角度显示一个刻度)
     * strokeColor: 描边颜色
     * lineWidth:线条宽度
     * moveX:起点x坐标
     * lineX:终点x坐标
    */
    function drawDial(ctx, num, angle, strokeColor, lineWidth, moveX, lineX) {
      for (let i = 0; i < num; i++) {
        ctx.save()
        ctx.translate(250, 250)
        ctx.rotate(i * angle * Math.PI / 180)
        ctx.beginPath()
        ctx.moveTo(moveX, 0)
        ctx.lineTo(lineX, 0)
        ctx.strokeStyle = strokeColor
        ctx.lineWidth = lineWidth
        ctx.lineCap = "round"
        ctx.closePath()
        ctx.stroke()
        ctx.restore()
      }
    }

	//绘制钟表
    function draw() {
      const myCanvas = document.getElementById('myCanvas');
      if (!myCanvas.getContext) return;
      const ctx = myCanvas.getContext('2d');

      const date = new Date()
      const seconds = date.getSeconds()
      const minutes = date.getMinutes();
      const hours = date.getHours();

      ctx.clearRect(0, 0, 500, 500)

      //绘制表盘背景
      ctx.save()
      ctx.translate(250, 250)
      ctx.beginPath();
      ctx.arc(0, 0, 100, 0, Math.PI * 2, false);
      ctx.fillStyle = "#fff";
      ctx.fill();
      ctx.restore()


      //绘制表盘刻度
      drawDial(ctx, 60, 6, 'rgba(0,0,0,.3)', 1, 85, 95)
      drawDial(ctx, 12, 30, 'rgba(0,0,0,.7)', 3, 80, 95)

      //绘制时分秒针
      drawClockWise(ctx, hours, 30, 'rgba(0,0,0,1)', 4, -60)
      drawClockWise(ctx, minutes, 6, 'rgba(0,0,0,.8)', 2.5, -70)
      drawClockWise(ctx, seconds, 6, 'rgba(0,0,0,.5)', 2, -80)
    }
    draw()

    setInterval(() => {
      draw()
    }, 1000)
  </script>
</body>

</html>
  • 12
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值