- <template>
- <!-- 降雨效果canvas -->
- <div class="canvasRainPage">
- <canvas id="canvasRainSS"></canvas>
- </div>
- </template>
-
- <script setup>
- const { proxy } = getCurrentInstance();
- const props = defineProps({
- width: { type: Number },
- height: { type: Number },
- });
- const timer = ref(null);
-
- // 画笔
- const ctx = ref(null);
- // 画布的宽高
- let w = props.width;
- let h = props.height;
- // 存放雨滴的数组
- let arr = [];
- // 雨滴的数量
- const size = ref(200);
- // 雨滴的构造函数
- 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, 0.6)';
- 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('#canvasRainSS');
- ctx.value = canvas.getContext('2d');
- canvas.width = w;
- canvas.height = h;
- init(ctx.value);
- }
-
- onMounted(() => {
- initCanvas();
- });
- onBeforeUnmount(() => {
- if (timer.value) clearInterval(timer.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>