[js] 突发奇想, 使用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>
    body {
      background-color: #10130f;
    }

    canvas {
      display: block;
      width: 800px;
      height: 800px;
      box-shadow: 2px 2px 10px 2px rgba(255, 255, 255, 1);
      margin: 20px auto 0;
    }
  </style>
</head>

<body>
  <canvas
    id="cvs"
    width="800"
    height="800"
  ></canvas>
  <script>
    const cvs = document.getElementById('cvs');
    const ctx = cvs.getContext('2d');
    const w = cvs.width;
    const h = cvs.height;
    const pi = Math.PI;
    ctx.lineWidth = 2
    ctx.translate(400, 400)


    // 绘制圆
    function drawCircle(rList) {
      ctx.beginPath();
      ctx.strokeStyle = "#06ea2f"
      for (let i = 0; i < rList.length; i++) {
        ctx.arc(0, 0, rList[i], 0, 2 * Math.PI);
        ctx.stroke();
      }
      ctx.closePath();
    }

    // 绘制直角坐标系
    function drawAxes() {
      ctx.beginPath();
      ctx.strokeStyle = "#06ea2f"
      ctx.moveTo(-370, 0);
      ctx.lineTo(370, 0);
      ctx.moveTo(0, -370);
      ctx.lineTo(0, 370);
      ctx.stroke();
      ctx.closePath();
    }

    // 绘制扫描线 弧度
    function drawScanLine(startDeg, endDeg) {
      ctx.beginPath();
      ctx.fillStyle = "#06ea2f"
      ctx.moveTo(w / 2, h / 2);
      const x1 = 370 * Math.cos(startDeg);
      const y1 = 370 * Math.sin(startDeg);
      const x2 = 370 * Math.cos(endDeg);
      const y2 = 370 * Math.sin(endDeg);
      ctx.moveTo(0, 0);
      ctx.lineTo(x1, y1);
      ctx.arc(0, 0, 370, startDeg, endDeg);
      ctx.fill()
      ctx.closePath();
    }

    // 绘制蒙版
    function drawMask() {
      ctx.beginPath()
      ctx.fillStyle = "rgba(16,19,15,.03)"
      ctx.fillRect(-400, -400, 800, 800)
      ctx.closePath()
    }

    // 起始角度
    let startAngle = 0;
    const speed = 1
    function draw() {
      drawMask()
      drawCircle([20, 90, 160, 230, 300, 370])
      drawAxes()
      // 计算弧度
      const startDeg = pi * 2 * ((startAngle - 1) / 360)
      const endDeg = pi * 2 * (startAngle / 360) + pi * 2 * speed / 360
      drawScanLine(startDeg, endDeg)
      startAngle += speed
      if (startAngle >= 360) {
        startAngle = 0
      }
      requestAnimationFrame(draw)
    }

    draw()
  </script>
</body>

</html>

结果如下, 会动的哟

 

posted @ 2024-11-13 11:35  深海里的星星i  阅读(0)  评论(0编辑  收藏  举报