canvas粒子游动动画效果代码

代码语言:html

所属分类:粒子

代码描述:canvas粒子游动动画效果代码

代码标签: canvas 粒子 游动 动画

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

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

<head>

  <meta charset="UTF-8">

  
  
<style>
canvas {
  cursor: crosshair;
  display: block;
}
</style>


</head>

<body  >
  <canvas ></canvas>


  
      <script>
let balls = [];
let _lastFrame = 0;

function init() {
  while (balls.length < 1024) {
    balls.push(
    new Ball(Math.random() * canvas.width, Math.random() * canvas.height, 8));

  }
  setInterval(() => {
    mouse.x = canvas.width / 2;
    mouse.y = canvas.height / 2;
  }, 1024 * 64);
}

function step(t) {
  if (fps >= 60) {
    // if (balls.length < 4096) {
    let a = Math.random() * 2 * Math.PI;
    balls.push(
    new Ball(
    canvas.width / 2 + Math.sin(a) * 1024,
    canvas.height / 2 + Math.cos(a) * 1024));


    // }
  } else if (balls.length > 8) {
    balls.pop();
  }
  _lastFrame = t;
  for (let ball of balls) {
    ball.update();
  }
  for (let i = 0; i < balls.length; i++) {
    for (let j = i + 1; j < balls.length; j++) {
      if (collides(balls[i], balls[j])) {
        balls[i].collide(balls[j]);
        balls[j].collide(balls[i]);
      }
    }
  }
  for (let ball of balls) {
    ball.draw();
  }
  g.fillStyle = "white";
  g.fillText("FPS: " + fps, 8, 16);
  g.fillText("Particles: " + balls.length, 8, 32);
}

function collides(a, b) {
  return Math.sqrt(sq(b.x - a.x) + sq(b.y - a.y)) < a.r + b.r;
}

function sq(n) {
  return n * n;
}

class Ball {
  constructor(x, y, r, c) {
    let v = Math.random() * 60;
    this.vx = 0;
    this.vy = 0;
    this.x = x || 0;
    this.y = y || 0;
    this.r = r || Math.random(); // * 12 + 12
    this.c = c || `hsl(${180 + v}, 100%, ${65 - v / 2}%)`;
    this.t_offset = Math.random() * Math.PI * 2;

    this._vx = Math.random() - 0.5;
    this._vy = Math.random() - 0.5;
    this._x = this.x;
    this._y = this.y;
  }

  gravitate(x, y, g = 1) {
    let dx = x - this.x;
    let dy = y - this.y;
    if (dx == 0 && dy == 0) {
      dx = Math.random();
      dy = Math.random();
    }
    let dist = Math.sqrt(sq(dx) + sq(dy));
    this.vx += dx / dist * g;
    this.vy += dy / dist * g;
  }

  update(t) {
    this.vx *= 0.999;
    this.v.........完整代码请登录后点击上方下载按钮下载查看

网友评论0