canvas彩色粒子线条连线动画效果代码

代码语言:html

所属分类:粒子

代码描述:canvas彩色粒子线条连线动画效果代码

代码标签: canvas 彩色 粒子 线条 连线 动画

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  

  
  
<style>
html, body {
  background: #000;
  padding: 0px;
  margin: 0px;
}

canvas {
  display: block;
}
</style>


  
  
</head>

<body translate="no">
  <canvas id="canvas"></canvas>
  
      <script >
let canvas = document.querySelector("#canvas"),
ctx = canvas.getContext("2d"),
w = 1500,
h = 260,
midX,midY,
particles = [];

let currentMaxParticles = 0;

const MaxParticles = 600,
ConnectionDist = 50,
MaxSpeed = 2.1,
Msqrt = Math.sqrt,
Mrandom = Math.random;

let attractPt = [
// {x:0, y:h*.5, force:260},
{ x: 0, y: h * .5, force: 255 }
// {x:0, y:h*.5, force:260},
];
let repelPt = [
// {x:0, y:h*.5, force:3, minDist:110},
{ x: 0, y: h * .5, force: 6, minDist: 85 }
// {x:0, y:h*.5, force:3, minDist:110},
];
let showAttractRepel = false;

const handleResize = () => {
  w = canvas.width = window.innerWidth;
  h = canvas.height = window.innerHeight;

  for (let i = 0; i < attractPt.length; i++) {
    attractPt[i].x = repelPt[i].x = w / 2; //(attractPt.length-1)*i;
    attractPt[i].y = repelPt[i].y = h / 2;
  }

  midX = w / 2;
  midY = h / 2;

  if (w < 450) {
    currentMaxParticles = Math.round(MaxParticles / 3);
  } else
  if (w >= 450 && w < 700) {
    currentMaxParticles = Math.round(MaxParticles / 1.5);
  } else
  {
    currentMaxParticles = MaxParticles;
  }
};
window.onresize = () => handleResize();
handleResize();

const createParticles = () => {
  let vRange = 1.5,
  vMin = .5,
  vx,vy;
  for (let i = 0; i < MaxParticles; i++) {
    vx = Mrandom() * vRange + vMin;
    vy = Mrandom() * vRange + vMin;
    if (Mrandom() > .5) {vx *= -1;}
    if (Mrandom() > .5) {vy *= -1;}
    particles.push({
      x: Mrandom() * w,
      y: Mrandom() * h,
      xv: Mrandom() * vx,
      yv: Mrandom() * vy });

  }
};

const update = () => {
  particles.forEach(p => {
    // move
    p.x += p.xv;
    p.y += p.yv;

    // keep in bounds
    if (p.x < 0) {
      p.x = 0;
      p.xv *= -1;
    } else
    if (p.x > w) {
      p.x = w;
      p.xv *= -1;
    }
    if (p.y < 0) {
      p.y = 0;
      p.yv *= -1;
    } else
    if (p.y > h) {
      p.y = h;
      p.yv *= -1;
    }

    // Attract
    attractPt.forEach(locus => {
      let dx = locus.x - p.x;
      let dy = locus.y - p.y;
      let distSQ = dx * dx + dy * dy;
      let dist = Msqrt(distSQ);
      force = locus.force / distSQ;
      p.xv += force * dx / dist;
      p.yv += force * dy / dist;
    });

    // Repel
    repelP.........完整代码请登录后点击上方下载按钮下载查看

网友评论0