canvas特效 圆点上升背景

在网上看到一个博客的背景,觉得挺好看的,看到使用的canvas,就来效仿了一下。博客地址

这里我把这个 canvas 作为背景来使用,做成了组件

展示效果如下

image
DOM 部分代码


注释都在代码中了 比较详细

data() {
    return {
      id: 'canvas' + this.$moment().format("x"), // 生成随机的id 这里使用了 moment 插件,可以自己定义id
      canvas: null,
      ctx: null,
      af: null,
    }
  },
  mounted() {
      // 初始化代码
      this.init()
      window.onresize = this.init;
  },
  methods: {
    init() {
        
      const numLasers = 400; // 生成圆点的数量
      this.canvas = document.getElementById(`${this.id}`);
      this.ctx = this.canvas.getContext("2d");
      this.canvas.width = window.innerWidth;
      this.canvas.height = window.innerHeight;
      cancelAnimationFrame(this.af); // 创建帧动画
      this.render(this.createLasers(numLasers)); // 开始生成元素
    },
    // 创建元素的方法
    createLasers(n) {
      const lasers = [];
      for (let i = 0; i < n; ++i) {
        lasers.push({
          x: Math.random() * this.canvas.width, // 水平方向的位置
          y: Math.random() * (1200 - this.canvas.height) + this.canvas.height, // 到达的位置
          maxY: (Math.random() * (this.canvas.height - 450) + 350), // 最高消失的点的位置
          s: Math.random() * 0.5 + 0.3, // 移动的速度
          r: Math.random() * (6 - 3) + 2.5 // 生成圆点的半径
        });
      }
      return lasers;
    },
    // 渲染到页面
    renderLaser(l) {
      this.ctx.beginPath();
      this.ctx.arc(l.x, l.y, l.r, 0, 2 * Math.PI, false); // 画圆
      this.ctx.fillStyle = 'rgba(255, 255, 255, .3)' // 填充圆
      this.ctx.strokeStyle = 'rgba(255, 255, 255, 0)';//填充边框颜色
      this.ctx.closePath();
      this.ctx.fill();
      this.ctx.moveTo(l.x, l); // 移动
      this.ctx.stroke();
    },
    // 移动圆的位置
    updateLaser(l) {
      l.y -= l.s;
      if (l.y < l.maxY) {
        l.y = this.canvas.height;
      }
    },
    render(lasers) {
      this.ctx.fillStyle = "rgba(255, 255, 255, 0)";
      // 需要注意的地方,清空画布,不然的话会显示运动轨迹,如果背景是纯色背景的可以不写
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
      for (let l of lasers) {
        this.renderLaser(l);
        this.updateLaser(l);
      }
      // 重复调用自身进行动画移动
      this.af = requestAnimationFrame(() => this.render(lasers));
    },

你可能感兴趣的:(canvas特效 圆点上升背景)