正文
动起来
雪动起来才能叫下雪,动起来很简单,不断改变
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) {// 让一小部分的雪初始化在左侧