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

本章完
相關文章
相關標籤/搜索