canvas粒子动画背景的实现示例

效果 :)

不带连线效果:

带连线的效果:

教程

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

创建canvas

首先需要在需要展示粒子背景的父元素中创建一个canvas标签, 指定widthheight, 在我们生成随机点坐标的时候需要用widthheight来做参照。widthheight等于父元素的宽和高。

// 假如父元素是bodyconst 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决定了点的运动轨迹。

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来改动点的位置。

// 调用draw函数开启动画(function draw() {  ctx.clearRect(0, 0, width, height);  drawPoints();  // 如果不需要画线,取消下面这行代码即可。  drawLines();  window.requestAnimationFrame(draw);}());

完整代码请看: https://github.com/PengJiyuan/particle-bg

我的Github:https://github.com/PengJiyuan

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

发表新评论