专栏名称: 伯乐在线
关注职业资讯;学习各类职业感悟、心得和经验分享,扩大职业视野;体会求职、工作和创业的历程 - 就在JobBole.com 伯乐在线
目录
相关文章推荐
稀土掘金技术社区  ·  用dayjs解析时间戳,我被提了bug ·  昨天  
码农翻身  ·  Excel终于要完蛋了吗? ·  17 小时前  
玉伯  ·  企业家要 ego ... ·  昨天  
OSC开源社区  ·  马建仓 AI ... ·  2 天前  
程序员的那些事  ·  疯了!我那些怀疑 AI ... ·  6 天前  
51好读  ›  专栏  ›  伯乐在线

冬天到了,女朋友想让我的网站也下雪,我立马打开电脑撸代码…

伯乐在线  · 公众号  · 程序员  · 2021-01-11 20:10

正文

请到「今天看啥」查看全文


动起来

雪动起来才能叫下雪,动起来很简单,不断改变 x y 坐标就可以了,给 snow 类加个运动的方法:

class snow {
    move () {
        this.x += this.speed
        this.y += this.speed
        this.el.style.left = this.x + 'px'
        this.el.style.top = this.y + 'px'
    }
}
复制代码

接下来使用 requestAnimationFrame 不断刷新:

moveSnow () {
    window.requestAnimationFrame(() => {
        snowList.forEach((item) => {
            item.move()
        })
        moveSnow()
    })
}
复制代码

效果如下,因为速度是正数,所以整体是往右斜的:

可以看到动起来了,但是出屏幕就不见了,所以雪是会消失的对吗?要让雪不停很简单,检测雪的位置,如果超出屏幕了就让它回到顶部,修改一下 move 方法:

move () {
    this.x += this.speed
    this.y += this.speed
    // 完全离开窗口就调一下初始化方法,另外还需要修改一下init方法,因为重新出现我们是希望它的y坐标为0或者小于0,这样就不会又凭空出现的感觉,而是从天上下来的
    if (this.x this.width || this.x > this.windowWidth || this.y > this.windowHeight) {
      this.init(true)
      this.setStyle()
    }
    this.el.style.left = this.x + 'px'
    this.el.style.top = this.y + 'px'
  }
复制代码
init (reset) {
    // ...
    this.width = Math.floor(Math.random() * this.maxWidth + this.minWidth)
    this.y = reset ? -this.width : Math.floor(Math.random() * this.windowHeight)
    // ...
  }
复制代码

这样就能源源不断的下雪了:

优化

1.水平速度

水平和垂直方向的速度是一样的,但是看起来有点太斜了,所以调整一下,把水平速度和垂直速度区分开来:

class Snow {
  constructor (opt = {}) {
    // ...
    // 水平速度
    this.sx = 0
    // 垂直速度
    this.sy = 0
  // ...
  }
  
  init (reset) {
    // ...
    this.sy = Math.random() * this.maxSpeed + this.minSpeed
    this.sx = this.sy * Math.random()
  }
  
  move () {
    this.x += this.sx
    this.y += this.sy
    // ...
  }
}
复制代码

2.左下角没有雪

因为整体向右倾斜,所以左下角大概率没有雪,这可以通过让雪随机出现在左侧来解决:

init (reset) {
  // ...
  this.x = Math.floor(Math.random() * (this.windowWidth - this.width))
  this.y = Math.floor(Math.random() * (this.windowHeight - this.width))
  if (reset && Math.random() > 0.8) {// 让一小部分的雪初始化在左侧






请到「今天看啥」查看全文