canvas实现流星雨坠落到地面砸出火花动画效果代码

代码语言:html

所属分类:动画

代码描述:canvas实现流星雨坠落到地面砸出火花动画效果代码

代码标签: canvas 流星雨 坠落 地面 砸出 火花 动画

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

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

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

  
  
  
<style>
body {
    margin: 0;
}

canvas {
    position: fixed;
    inset: 0;
    background-color: #000;
}
</style>


  
  
</head>

<body >
  <canvas id="main-canvas"></canvas>
  
      <script  >
const canvas = document.getElementById('main-canvas');
const c = canvas.getContext('2d');

var cw = canvas.width = innerWidth;
var ch = canvas.height = innerHeight;

var elements = [];

var gravity = .25;
var friction = .5;


class Particles {
  constructor({ x, y, r, color, velocity, comet, type = 'particle' }) {
    this.x = x;
    this.ox = x;
    this.y = y;
    this.oy = y;

    this.r = r;
    this.color = color;

    this.velocity = velocity;
    this.opacity = Math.random() * 100;
    this.comet = comet;
    this.exploded = false;
    this.type = type;


  }

  draw() {
    c.save();
    c.beginPath();

    c.globalAlpha = this.opacity / 100;
    c.fillStyle = this.color;
    c.arc(this.x, this.y, this.r, 0, Math.PI * 2);
    c.fill();

    c.closePath();
    c.restore();
  }

  update() {
    this.draw();

    this.x += this.velocity.x;
    this.y += this.velocity.y;
    if (this.type == 'explotion') {
      this.velocity.y += gravity;
      this.opacity -= .5;
    } else
    this.opacity -= randomFloat(1, 3);

    if (this.y + this.r > ch) {
      this.velocity.y = -this.velocity.y * friction;
    }

    if (this.opacity <= 0) {
      if (this.type == 'explotion') this.comet.explotions.splice(this.comet.explotions.indexOf(this), 1);else
      this.reset();
    }
  }

  reset() {
    this.opacity = Math.floor(randomFloat(25, 50));
    this.x = randomFloat(
    this.comet.x - this.r + this.comet.r,
    this.comet.x + this.r - this.comet.r);


    this.y = this.comet.y;
  }}


class Comet {
  constructor({ x, y, r, color, velocity }) {
    this.x = x;
    this.y = y;
    this.r = r;
    this.color = color;

    this.velocity = velocity;
    this.tails = this.generateTail();
    this.explotions = [];

  }

  generateTail() {
    const tails = [];

    for (let i = 0; i < 50; i++) {
      const radius = randomFloat(1, 3);

      tails.push(new Par.........完整代码请登录后点击上方下载按钮下载查看

网友评论0