<template>
  <canvas ref="waveCanvas" class="wave-canvas"></canvas>
</template>

<script>
export default {
  name: "WaveCanvas",
  data() {
    return {
      animationId: null,
      time: 0,
      waves: [
        {
          height: 12,
          speed: 0.03,
          length: 0.05,
          color: "rgba(0, 222, 255, 0.6)",
          offsetY: 0,
        },
        {
          height: 9,
          speed: 0.05,
          length: 0.055,
          color: "rgba(0, 180, 255, 0.5)",
          offsetY: 2,
        },
        {
          height: 6,
          speed: 0.04,
          length: 0.056,
          color: "rgba(0, 150, 255, 0.4)",
          offsetY: 2,
        },
      ],
    };
  },
  mounted() {
    this.initCanvas();
    this.startAnimation();
  },
  beforeDestroy() {
    cancelAnimationFrame(this.animationId);
  },
  methods: {
    initCanvas() {
      const canvas = this.$refs.waveCanvas;
      canvas.width = 337;
      canvas.height = 47;
    },
    drawWave() {
      const canvas = this.$refs.waveCanvas;
      const ctx = canvas.getContext("2d");
      const width = canvas.width;
      const height = canvas.height;

      ctx.clearRect(0, 0, width, height);

      // 绘制多层波浪
      this.waves.forEach((wave) => {
        ctx.beginPath();
        ctx.moveTo(0, height);

        // 创建波浪路径
        const points = [];
        for (let i = -20; i <= width + 20; i += 5) {
          const x = i;
          const y =
            height -
            20 +
            wave.offsetY +
            Math.sin(x * wave.length + this.time * wave.speed) * wave.height;
          points.push({ x, y });
        }

        // 绘制贝塞尔曲线
        ctx.moveTo(0, points[0].y);
        for (let i = 1; i < points.length; i++) {
          const xc = (points[i].x + points[i - 1].x) / 2;
          const yc = (points[i].y + points[i - 1].y) / 2;
          ctx.quadraticCurveTo(points[i - 1].x, points[i - 1].y, xc, yc);
        }

        // 闭合路径
        ctx.lineTo(width, height);
        ctx.lineTo(0, height);

        ctx.fillStyle = wave.color;
        ctx.fill();
      });
    },
    startAnimation() {
      const animate = () => {
        this.time += 0.5;
        this.drawWave();
        this.animationId = requestAnimationFrame(animate);
      };
      animate();
    },
  },
};
</script>

<style scoped lang="scss">
.wave-canvas {
  position: absolute;
  width: 337px;
  height: 47px;
  overflow: hidden; // 确保内容不会溢出
}
</style>
