Newer
Older
KaiFengPC / src / views / sponeScreen / cityGK / canvasRain.vue
@zhangdeliang zhangdeliang on 3 Sep 2 KB update
<template>
  <!-- 降雨效果canvas -->
  <div class="canvasRainPage">
    <canvas id="canvasRain"></canvas>
  </div>
</template>

<script setup>
const { proxy } = getCurrentInstance();
const timer = ref(null);
const timerAll = ref(null);

// 画笔
const ctx = ref(null);
// 画布的宽高
let w = window.innerWidth;
let h = window.innerWidth;
// 存放雨滴的数组
let arr = [];
// 雨滴的数量
const size = ref(300);
// 雨滴的构造函数
class Rain {
  x = random(w);
  y = random(h);
  ySpeed = random(2) + 8;
  show() {
    drawLine(this.x, this.y);
  }
  run() {
    if (this.y > h) {
      this.y = 0;
      this.x = random(w);
    }
    this.y = this.y + this.ySpeed;
  }
}
// 画线(雨滴)
function drawLine(x1, y1) {
  ctx.value.beginPath();
  ctx.value.strokeStyle = 'rgba(35, 195, 255, 1)';
  ctx.value.moveTo(x1, y1);
  // 雨长度
  ctx.value.lineTo(x1, y1 + 20);
  ctx.value.stroke();
}
// 生成随机数
function random(num) {
  return Math.random() * num;
}
// 开始
function start() {
  for (let i = 0; i < size.value; i++) {
    let rain = new Rain();
    arr.push(rain);
    rain.show();
  }
  timer.value = setInterval(() => {
    ctx.value.clearRect(0, 0, w, h);
    for (let i = 0; i < size.value; i++) {
      arr[i].show();
      arr[i].run();
    }
  }, 30);
}
// 初始化
function init(ctx1) {
  ctx.value = ctx1;
  start();
}

// 清除画布
function clearDraw() {
  ctx.value.clearRect(0, 0, w, h);
}

// 初始化
function initCanvas() {
  const canvas = document.querySelector('#canvasRain');
  ctx.value = canvas.getContext('2d');
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  init(ctx.value);
  // 1-12个月的不同降雨量变化
  let rainArr = [
    { month: '1', rain: 300 },
    { month: '2', rain: 350 },
    { month: '3', rain: 400 },
    { month: '4', rain: 450 },
    { month: '5', rain: 550 },
    { month: '6', rain: 600 },
    { month: '7', rain: 1200 },
    { month: '8', rain: 700 },
    { month: '9', rain: 600 },
    { month: '10', rain: 460 },
    { month: '11', rain: 400 },
    { month: '12', rain: 300 },
  ];
  let i = 0;
  timerAll.value = setInterval(() => {
    size.value = rainArr[i].rain;
    i++;
    if (i == 12) i = 0;
    init(ctx.value);
  }, 1500);
}

onMounted(() => {
  initCanvas();
});
onBeforeUnmount(() => {
  if (timer.value) clearInterval(timer.value);
  if (timerAll.value) clearInterval(timerAll.value);
  clearDraw();
});
</script>

<style lang="scss" scoped>
.canvasRainPage {
  width: 100%;
  height: 100%;
  background: rgba(0, 59, 109, 0.2);
  position: absolute;
  left: 0px;
  top: 0px;
  z-index: 100;
  pointer-events: none;
}
</style>