canvas 星空特效

余生长醉 提交于 2020-03-01 10:39:01

阿里云图标首页背景–星空特效

效果
星空特效

代码

<html>
<canvas id="_bgcanvas" style="position: fixed;z-index:-1"></canvas>
<script>

/**
 * 
 * @param {string} element  canvas 元素  
 * @param {int} width    宽
 * @param {int} height  高
 */
function xingkong (element, width, height) {
  
  var canvas = document.querySelector(element);
  var w = width ||document.documentElement.clientWidth;
  var h = height || document.documentElement.clientHeight;
  canvas.width = w, canvas.height = h;
  var context = canvas.getContext("2d");

  // 背景
  context.fillStyle = "#090723";
  context.fillRect(0, 0, w, h);

  for (var l = [], r = 0; r < h; r += 4){
    l.push(new t({ x: Math.random() * w, y: Math.random() * h }));
  }
  l.push(new e);
  l.push(new e);
  function run () {
    context.fillStyle = "#090723",
    context.fillRect(0, 0, w, h);
    var n = "rgba(255, 255, 255, 0.5)";
    context.fillStyle = n;
    context.strokeStyle = n;
    for (var t = l.length; t--;) {
      l[t].update();
      
    }
    window.requestAnimationFrame(run)
  }
  
  run()

  // 星星
  function t (c) {

    this.size = 2 * Math.random();
    this.speed = .07 * Math.random();
    this.x = c.x;
    this.y = c.y

    // 
    this.reset = function () {
      this.size = 2 * Math.random();
      this.speed = .05 * Math.random();
      this.x = w;
      this.y = Math.random() * h;
    } 

    this.update = function  ()
    { 
      this.x -= this.speed, this.x < 0 ? this.reset() : context.fillRect(this.x, this.y, this.size, this.size)
    }
  }
  
  // 流星
  function e () {
    this.reset = function  () {
      this.x = Math.random() * w;
      this.y = 0;
      this.len = 80 * Math.random() + 10;
      this.speed = 8 * Math.random() + 4;
      this.size = +Math.random() + .1;
      this.waitTime = (new Date).getTime() + 3e3 * Math.random() + 500, this.active = !1
    }

    this.update = function ()
    {
      if(this.active == undefined)
        this.reset()
      this.active ?
        (this.x -= this.speed,
          this.y += this.speed,
          this.x < 0 || this.y >= height ? this.reset() : (context.lineWidth = this.size, context.beginPath(),
          context.moveTo(this.x, this.y),
          context.lineTo(this.x + this.len, this.y - this.len), context.stroke()))
        : this.waitTime < (new Date).getTime() && (this.active = !0)
    }
    
  }

}

// 使用
new xingkong("#_bgcanvas")
</script>
</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!