在vue中使用canvas实现下雨特效

效果展示

在页面中添加canvas标签
<template>
  <div class="home">
    <canvas id="canvas" />
  </div>
</template>
初始化canvas
initCanvas() {
      const canvas = document.querySelector("#canvas");
      this.ctx = canvas.getContext("2d");
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
      init(this.ctx);
},

页面全部代码

<template>
  <div class="home">
    <canvas id="canvas" />
    <!-- 换成自己的图片 -->
    <img :style="canvasStyle" src="../assets/pic121.jpg" />
  </div>
</template>

<script>
import { init } from "@/components/rain.js";

export default {
  name: "Home",
  data() {
    return {
      canvasStyle: {
        position: "fixed",
        width: "100%",
        height: "100%",
        zIndex: "-1",
        left: "0",
        bottom: "0",
      },
      ctx: {},
    };
  },
  mounted() {
    this.initCanvas();
  },
  methods: {
    initCanvas() {
      const canvas = document.querySelector("#canvas");
      this.ctx = canvas.getContext("2d");
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
      init(this.ctx);
    },
  },
};
</script>

创建rain.js

// 画笔
var ctx;
// 画布的宽高
var w = window.innerWidth;
var h = window.innerWidth;
// 存放雨滴的数组
var arr = [];
// 雨滴的数量
var size = 150;
// 雨滴的构造函数
class Rain {
  x = random(w);
  y = random(h);
  ySpeed = random(2) + 5;
  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.beginPath();
  ctx.strokeStyle = "#cccccc";
  ctx.moveTo(x1, y1);
  // 雨长度为30
  ctx.lineTo(x1, y1 + 30);
  ctx.stroke();
}
// 生成随机数
function random(num) {
  return Math.random() * num;
}
// 开始
function start() {
  for (var i = 0; i < size; i++) {
    var rain = new Rain();
    arr.push(rain);
    rain.show();
  }
  setInterval(() => {
    ctx.clearRect(0, 0, w, h);
    for (var i = 0; i < size; i++) {
      arr[i].show();
      arr[i].run();
    }
  }, 10);
}
// 初始化
function init(ctx1) {
  ctx = ctx1;
  start();
}
// 导出初始化函数
export { init };

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值