/**
 *@author liuhaixiao
 *@createTime 2018-12-13 09:03
 *@description 下雨动效
 */
var rainArray = [];
var rainHeight = 20;
export default class Rain {

  random(min, max) {
    return Math.random() * (max - min) + min;
  }

  constructor(select) {
    this.oC = select;
    this.widthCanvas = this.oC.width;
    this.heightCanvas = this.oC.height;
    this.oGc = this.oC.getContext('2d');
  }

  init() {
    this.x = this.random(0, this.widthCanvas);//圆的中心的 x 坐标。
    this.y = this.random(-100, 10);//圆的中心的 y 坐标。
    this.r = 2;//圆的半径。

    this.vy = this.random(2, 20);//y坐标的变化值（主要作用是控制Y坐标下落的速度）
  }

  draw(cxt) {
    this.color = cxt.createLinearGradient(this.x, this.y, this.x, this.y + rainHeight);
    this.color.addColorStop(0,'rgba(255, 255, 255, 0');
    this.color.addColorStop(1,'rgba(255, 255, 255, 0.25)');
    cxt.strokeStyle = this.color;
    // cxt.strokeStyle = 'red';//为了测试把颜色调整成红色代码
    cxt.beginPath();//起始一条路径，或重置当前路径
    cxt.moveTo(this.x, this.y);
    cxt.lineWidth = 1;
    cxt.lineTo(this.x , this.y + rainHeight);
    cxt.stroke();
    this.update();
  }

  update() {
    if (this.y < this.heightCanvas - this.r) {
      this.y += this.vy;
    } else {
      this.init();
    }
  }

  process() {
    if (rainArray.length <= 10) {
      for (var i = 0; i < 10; i++) {
        setTimeout(() => {
          var oRain = new Rain(this.oC);
          oRain.init();
          rainArray.push(oRain);
        }, 1000 * i);
      }
    }
    this.oGc.clearRect(0, 0, this.widthCanvas, this.heightCanvas + rainHeight)
    for (var i = 0; i < rainArray.length; i++) {
      rainArray[i].draw(this.oGc);
    }
    requestAnimationFrame(this.process.bind(this));


  }
}
