html 用 canvas 繪制波浪線 正弦函數的妙用


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      canvas {
        background-color: #eee;
        /* background-color: rgba(204, 119, 238, .5); */
      }
    </style>
  </head>
  <body>
    <canvas width="600" height="600"></canvas>

    <script>
      const canvas = document.querySelector("canvas");
      const width = canvas.width;
      const height = canvas.height;
      const ctx = canvas.getContext("2d");

      const A = 40; // 正弦函數范圍 -1 到 1, 擴大 120 倍 就是 -120 到 120
      const offset = height / 2;
      const translateX = Math.PI / 10;
      const speed = 100;
      const time = 10;

      ctx.beginPath();
      ctx.arc(300, 300, 202, 0, Math.PI * 2);
      ctx.strokeStyle = "#222";
      ctx.lineWidth = 2;
      ctx.stroke();

      function sinX(x, m) {
        return Number((A * Math.sin(x + m) + offset).toFixed(2));
      }

      let start = 0;
      let start2 = 0;
      const addInc = 10;
      setInterval(() => {
        start += Math.PI / addInc;
        start2 += Math.PI / addInc / 2;

        ctx.clearRect(0, 0, width, height);
        ctx.save();
        ctx.beginPath();
        draw(start, "rgba(199, 237, 204, 0.5)");
        ctx.beginPath();
        draw(start2 + Math.PI, "rgba(204, 119, 238, .5);");
      }, speed);

      function draw(tra, color) {
        ctx.fillStyle = color;
        ctx.moveTo(0, sinX(0, tra));
        let lastPoint = [0, 300];
        for (let i = 0; i < 2 * Math.PI; i += Math.PI / 50) {
          const inc = width / Math.PI / 2;
          const point = [Number((i * inc).toFixed(2)), sinX(i, tra)];
          ctx.lineTo(...point);
        }
        ctx.moveTo(600, sinX(2 * Math.PI, tra));
        ctx.lineTo(600, 600);
        ctx.lineTo(0, 600);
        ctx.lineTo(0, sinX(0, tra));
        ctx.fill();
      }

      ctx.arc(300, 300, 200, 0, Math.PI * 2);
      ctx.clip();
      ctx.fill();
      ctx.restore();
      ctx.moveTo(0, 0);
      ctx.lineTo(600, 600);
      ctx.stroke();
    </script>
  </body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM