canvas粒子动画背景

效果 :)

不带连线效果:
clipboard.pngjavascript

带连线的效果:
clipboard.pngjava

教程

要实现这样的效果其实很简单,大概分为这么几个步骤:git

建立canvas

首先须要在须要展现粒子背景的父元素中建立一个canvas标签, 指定widthheight, 在咱们生成随机点坐标的时候须要用widthheight来作参照。widthheight等于父元素的宽和高。github

// 假如父元素是body
const ele = document.body;
const canvas = document.createElement('canvas');
canvas.width = ele.clientWidth;
canvas.height = ele.clientHeight;
// 将canvas标签插入
ele.appendChild(canvas);

随机生成必定数量的点坐标信息

widthheight作参照随机生成必定数量的点坐标信息,包含x, y, rateX(点在X轴的移动速率), rateY(点在Y轴移动的速率), rateXrateY决定了点的运动轨迹。canvas

const points = [];
// 随机生成点的坐标,需指定radius的最大值
function getPoint(radius) {
  const x = Math.ceil(Math.random() * this.width), // 粒子的x坐标
    y = Math.ceil(Math.random() * this.height), // 粒子的y坐标
    r = +(Math.random() * this.radius).toFixed(4), // 粒子的半径
    rateX = +(Math.random() * 2 - 1).toFixed(4), // 粒子在x方向运动的速率
    rateY = +(Math.random() * 2 - 1).toFixed(4); // 粒子在y方向运动的速率

  return { x, y, r, rateX, rateY };
}

// 随机生成100个点的坐标信息
for (let i = 0; i < 100; i++) {
  points.push(this.getPoint());
}

将生成的点数组画到canvas上

function drawPoints() {
  points.forEach((item, i) => {
    ctx.beginPath();
    ctx.arc(item.x, item.y, item.r, 0, Math.PI*2, false);
    ctx.fillStyle = '#fff';
    ctx.fill();
    // 根据rateX和rateY移动点的坐标
    if(item.x > 0 && item.x < width && item.y > 0 && item.y < height) {
      item.x += item.rateX * rate;
      item.y += item.rateY * rate;
    } else {
      // 若是粒子运动超出了边界,将这个粒子去除,同时从新生成一个新点。
      points.splice(i, 1);
      points.push(getPoint(radius));
    }
  });
}

画线

遍历点数组,两两比较点坐标,若是两点之间距离小于某个值,在两个点之间画一条直线,lineWidth随两点之间距离改变,距离越大,线越细。数组

// 计算两点之间的距离
function dis(x1, y1, x2, y2) {
  var disX = Math.abs(x1 - x2),
    disY = Math.abs(y1 - y2);

  return Math.sqrt(disX * disX + disY * disY);
}

function drawLines() {
  const len = points.length;
  //对圆心坐标进行两两判断
  for(let i = 0; i < len; i++) {
    for(let j = len - 1; j >= 0; j--) {
      const x1 = points[i].x,
        y1 = points[i].y,
        x2 = points[j].x,
        y2 = points[j].y,
        disPoint = dis(x1, y1, x2, y2);

      // 若是两点之间距离小于150,画线
      if(disPoint <= 150) {
        ctx.beginPath();
        ctx.moveTo(x1, y1);
        ctx.lineTo(x2, y2);
        ctx.strokeStyle = '#fff';
        //两点之间距离越大,线越细,反之亦然
        ctx.lineWidth = 1 - disPoint / distance;
        ctx.stroke();
      }
    }
  }
}

动画

使用requestAnimationFrame循环调用draw方法(draw方法里包含画点和画线),同时在draw的时候根据rateXrateY来改动点的位置。app

// 调用draw函数开启动画
(function draw() {
  ctx.clearRect(0, 0, width, height);
  drawPoints();
  // 若是不须要画线,取消下面这行代码便可。
  drawLines();
  window.requestAnimationFrame(draw);
}());
完整代码请看: https://github.com/PengJiyuan...

个人Github:https://github.com/PengJiyuandom

本章完
相关文章
相关标签/搜索