原生js实现canvas下雨动画效果代码

代码语言:html

所属分类:粒子

代码描述:原生js实现canvas下雨动画效果代码

代码标签: canvas 下雨 动画 效果

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

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas下雨</title>

<style>
body {
  background: #0c0c0c;
}
</style>

</head>
<body>


<script>
(function (window, document) {
  var Vector2 = (function () {
    function Vector2(x, y) {
      this.x = x || 0;
      this.y = y || 0;
    }
    return Vector2;
  })();

  Vector2.prototype.add = function (addend) {
    this.x += addend.x;
    this.y += addend.y;
  };

  var RainDrop = (function () {
    function RainDrop(parent) {
      this.size = 2;
      this.parent = parent;
      this.init();
    }
    return RainDrop;
  })();

  RainDrop.prototype.init = function () {
    this.life = 0;
    this.ttl = Math.random() * 500 + 300;
    this.position = new Vector2(Math.random() * window.innerWidth, 0);
    this.velocity = new Vector2(
      0.5 - Math.random() * 1,
      Math.random() * 1 + 0.2
    );
    this.terminalVelocity = 8;
  };

  RainDrop.prototype.update = function () {
    if (
      this.position.x > window.innerWidth ||
      this.position.x < -this.size ||
      this.life > this.ttl
    )
      this.init();
    if (this.position.y > this.parent.floor) {
      this.position.y = this.parent.floor - this.size;
      this.velocity.y *= -0.2 - Math.random() * 0.2;
    }
    this.life++;
    this.position.add(this.velocity);
    this.velocity.y += 0.1;
  };

  var Rain = (function () {
    function Rain(args) {
      this.props = args;
      this.rainDrops = [];
      this.init();
    }
    return Rain;
  })();

  Rain.prototype.init = function () {
    this.createCanvas();
    this.resize();
    this.loop();
  };

  Rain.prototype.resize = function () {
    var attr =
      "position: absolute; z-index: 0; top: 0; left: 0; height: 100vh; width: 100vw;";

    this.canvas.setAttribute("style", attr);

    this.dimensions = {
      width: window.innerWidth,
      height: window.innerHeight
    };

    this.canvas.width = this.dimensions.width;
    this.canvas.height = this.dimensions.height;
    this.floor = this.dimensions.height * 0.7;
  };

  Rain.prototype.createCanvas = function () {
    this.canvas = document.createElement("canvas");

    this.ctx = this.canvas.getContext("2d");

    document.body.appendChild(this.canvas);
  };

  Rain.prototype.draw = fu.........完整代码请登录后点击上方下载按钮下载查看

网友评论0