原生js模拟粒子碰撞动画效果

代码语言:html

所属分类:粒子

代码描述:原生js模拟粒子碰撞动画效果

代码标签: 粒子 碰撞 动画 效果

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

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">

<style>
body {
    margin: 0;
    background: #000;
    color: #fff;
    overflow: hidden;
}

canvas {
    display: block;
    width: 100vw;
    height: 100vh;
}
</style>

</head>
<body translate="no">
<canvas></canvas>

<script >
const rand = (a, b) => a + Math.floor(Math.random() * (b - a + 1));
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

const numParticles = Math.floor(innerWidth * innerHeight * 7e-4);
const pixelSizeX = 6;
const pixelSizeY = 6;
const gridX = 10;
const gridY = 10;

class Particle {

  constructor() {
    this.pixelSizeX = rand(4, 8);
    this.pixelSizeY = rand(4, 8);
    this.setRandomPosition();
    this.setRandomColor();
    this.setRandomDirection();

  }

  setRandomDirection() {
    const d = rand(0, 1) ? -1 : 1;
    if (rand(0, 1) === 0) {
      this.xr = 0;
      this.yr = d;
    } else {
      this.xr = d;
      this.yr = 0;
    }
  }

  setRandomColor() {
    this.color =
    "#" +
    rand(0, 15).toString(16) +
    rand(0, 15).toString(16) +
    rand(0, 15).toString(16);
  }

  get maxX() {
    return Math.floor(innerWidth / this.pixelSizeX);
  }

  get maxY() {
    return Math.floor(innerHeight / this.pixelSizeY);
  }


  setRandomPosition() {
    this.x = rand(0, this.maxX);
    this.y = rand(0, this.maxY);
  }

  distanceTo(p) {
    const x0 = this.x * this.pixelSizeX;
    const y0 = this.y * this.pixelSizeY;
    const x1 = p.x * p.pixelSizeX;
    const y1 = p.y * p.pixelSizeY;
    const dx = Math.abs(x0 - x1);
    const dy = Math.abs(y0 - y1);
    return Math.sqrt(dx ** 2 + dy ** 2);
  }


  draw() {
    const { pixelSizeX, pixelSizeY } = this;
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x * pixelSizeX, this.y * pixelSizeY, pixelSizeX, pixe.........完整代码请登录后点击上方下载按钮下载查看

网友评论0