canvas 星空特效

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

效果
星空特效

代码

<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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hobtdto

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值