冬天到了,给你的网站下个雪吧

简介: 冬天到了,给你的网站下个雪吧

前言


女朋友常逛的设计网站这两天页面上多了下雪的效果,于是问我我的网站能下雪吗,作为一个程序员我一般会说实现不了,但是作为男朋友,不能说不行。


雪


雪我们可以使用span标签和css的径向渐变简单意思一下:


.snow {
  display: block;
  width: 100px;
  height: 100px;
  background-image: radial-gradient(#fff 0%, rgba(255, 255, 255, 0) 60%);
  border-radius: 50%;
}


效果如下:


image.png


很多雪


一片雪是不够的,成千上万才浪漫,世界上没有两片相同的雪花,所以每片雪都有自己的大小位置速度等属性,为此先创建一个雪花类:


class Snow {
  constructor (opt = {}) {
    // 元素
    this.el = null
    // 直径
    this.width = 0
    // 最大直径
    this.maxWidth = opt.maxWidth || 80
    // 最小直径
    this.minWidth = opt.minWidth || 2
    // 透明度
    this.opacity = 0
    // 水平位置
    this.x = 0
    // 重置位置
    this.y = 0
    // 速度
    this.speed = 0
    // 最大速度
    this.maxSpeed = opt.maxSpeed || 4
    // 最小速度
    this.minSpeed = opt.minSpeed || 1
    // 浏览器窗口尺寸
    this.windowWidth = window.innerWidth
    this.windowHeight = window.innerHeight
    this.init()
  }
  // 初始化各种属性
  init () {
    this.width = Math.floor(Math.random() * this.maxWidth + this.minWidth)
    this.opacity = Math.random()
    this.x = Math.floor(Math.random() * (this.windowWidth - this.width))
    this.y = Math.floor(Math.random() * (this.windowHeight - this.width))
    this.speed = Math.random() * this.maxSpeed + this.minSpeed
  }
  // 设置样式
  setStyle () {
    this.el.style.cssText = `
      position: fixed;
      left: 0;
      top: 0;
      display: block;
      width: ${this.width}px;
      height: ${this.width}px;
      opacity: ${this.opacity};
      background-image: radial-gradient(#fff 0%, rgba(255, 255, 255, 0) 60%);
      border-radius: 50%;
      z-index: 9999999999999;
      pointer-events: none;
      transform: translate(${this.x}px, ${this.y}px);
    `
  }
  // 渲染
  render () {
    this.el = document.createElement('div')
    this.setStyle()
    document.body.appendChild(this.el)
  }
}


init方法用来生成随机的初始大小、位置、速度等属性,在浏览器窗口内new100片试试:


let snowList = []
for (let i = 0; i < 100; i++) {
    let snow = new Snow()
    snow.render()
    snowList.push(snow)
}


效果如下:


image.png


动起来


雪动起来才能叫下雪,动起来很简单,不断改变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()
    })
}


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


image.png


可以看到动起来了,但是出屏幕就不见了,所以雪是会消失的对吗?要让雪不停很简单,检测雪的位置,如果超出屏幕了就让它回到顶部,修改一下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)
    // ...
  }


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


image.png


优化


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
    // ...
  }
}


image.png


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) {// 让一小部分的雪初始化在左侧
    this.x = -this.width
  } else if (reset) {
    this.y = -this.width
  }
  // ...
}


3.眼前的雪


随机性的选择一点雪给它较大的体积、透明度和速度,然后再使用css3的3D透视效果,把它的z轴数值调大一点,这样的感觉就好像是在眼前划过的一样:


<body style="perspective: 500;-webkit-perspective: 500"></body>


class Snow {
  constructor (opt = {}) {
    // ...
    // z轴数值
    this.z = 0
    // 快速划过的最大速度
    this.quickMaxSpeed = opt.quickMaxSpeed || 10
    // 快速划过的最小速度
    this.quickMinSpeed = opt.quickMinSpeed || 8
    // 快速划过的宽度
    this.quickWidth = opt.quickWidth || 80
    // 快速划过的透明度
    this.quickOpacity = opt.quickOpacity || 0.2
    // ...
  }
  init (reset) {
    let isQuick = Math.random() > 0.8
    this.width = isQuick ? this.quickWidth : Math.floor(Math.random() * this.maxWidth + this.minWidth)
    this.z = isQuick ? Math.random() * 300 + 200 : 0
    this.opacity = isQuick ? this.quickOpacity : Math.random()
    // ...
    this.sy = isQuick ? Math.random() * this.quickMaxSpeed + this.quickMinSpeed : Math.random() * this.maxSpeed + this.minSpeed
    // ...
  }
  move () {
    // ...
    this.el.style.transform = `translate3d(${this.x}px, ${this.y}px, ${this.z}px)`
  }
}


image.png


4.鹅毛大雪


雪花嘛,轻如鹅毛,鹅毛是怎么飘的?是不是左右摆动的飘?那我们也可以选择一部分的雪花让它跟鹅毛一样飘,左右摇摆很简单,速度一会加一会减就可以了:


class Snow {
  constructor (opt = {}) {
    // ...
    // 是否左右摇摆
    this.isSwing = false
    // 左右摇摆的步长
    this.stepSx = 0.03
    // ...
  }
  // 随机初始化属性
  init (reset) {
    // ...
    this.isSwing = Math.random() > 0.8
    // ...
  }
  move () {
    if (this.isSwing) {
      if (this.sx >= 1 || this.sx <= -1) {
        this.stepSx = -this.stepSx
      }
      this.sx += this.stepSx
    }
    // ...
  }
}


image.png


除了上述这种方法,左右摇摆还有一种方式,就是使用正弦或余弦函数,因为它们的曲线翻转90度就是左右摇摆:


image.png


我们使用正弦函数,公式为:y=sin(x),x的值是弧度表示,只要一直增加就可以了,y的值用来修改雪花的水平方向的速度变化步长:


class Snow {
  constructor (opt = {}) {
    // ...
    // 是否左右摇摆
    this.isSwing = false
    // 左右摇摆的正弦函数x变量
    this.swingRadian = 0
    // 左右摇摆的正弦x步长
    this.swingStep = 0.01
    // ...
  }
  init (reset) {
    // ...
    this.swingStep = 0.01 * Math.random()
  }
  move () {
    if (this.isSwing) {
      this.swingRadian += this.swingStep
      this.x += this.sx * Math.sin(this.swingRadian * Math.PI) * 0.2
    } else {
      this.x += this.sx
    }
    // ...
  }
}


因为正弦函数y的值是从1变化到-1,摆动幅度太了,所以乘了个小数0.2缩小一点,想要幅度小一点,还有一个方法是不要使用整个正弦曲线,可以从中截取一个适合的区间大小,比如就让x的值在0.9π到1.1π之前变化:


class Snow {
  constructor (opt = {}) {
    // ...
    // 是否左右摇摆
    this.isSwing = false
    // 左右摇摆的正弦函数x变量
    this.swingRadian = 1// 需要改成一个中间值
    // 左右摇摆的正弦x步长
    this.swingStep = 0.01
    // ...
  }
  init (reset) {
    // ...
    this.swingStep = 0.01 * Math.random()
    this.swingRadian = Math.random() * (1.1 - 0.9) + 0.9// 也让它随机一下
  }
  move () {
    if (this.isSwing) {
      if (this.swingRadian > 1.1 || this.swingRadian < 0.9) {
        this.swingStep = -this.swingStep
      }
      this.swingRadian += this.swingStep
      this.x += this.sx * Math.sin(this.swingRadian * Math.PI)
    } else {
      this.x += this.sx
    }
    // ...
  }
}


5.下的慢一点


既然给水平加了曲线,垂直方向上是不是也可以改成非匀速呢?当然可以,区别是速度得一直是正的,不然就要出现反自然现象了,改变速度曲线同样可以使用正余弦,上面我们使用了0.9π到1.1π之间的正弦曲线,根据上图可以发现对应的余弦曲线都是负的,趋势是先慢后快,所以可以利用这一段来改变垂直方向的速度:


image.png


move () {
  if (this.isSwing) {
    if (this.swingRadian > 1.1 || this.swingRadian < 0.9) {
      this.swingStep = -this.swingStep
    }
    this.swingRadian += this.swingStep
    this.x += this.sx * Math.sin(this.swingRadian * Math.PI)
    this.y -= this.sy * Math.cos(this.swingRadian * Math.PI)// 因为速度都是负的,所以改成-
  } else {
    this.x += this.sx
    this.y += this.sy
  }
  // ...
}


6.在最上面


为了防止为页面上原本层级更高的元素遮挡,给雪花的样式加一个很大的层级:


render () {
    this.el = document.createElement('div')
    this.el.style.cssText = `
        // ...
        z-index: 9999999999999;
    `
    document.body.appendChild(this.el)
}


7.看不见我


修改了层级,所以雪花会在页面的最上层,那么可能会挡住其他元素的鼠标事件,需要禁止它响应鼠标事件:


render () {
    this.el = document.createElement('div')
    this.el.style.cssText = `
      // ...
      pointer-events: none;
    `
    document.body.appendChild(this.el)
  }


8.更好一点


使用性能更好的transform属性来做动画:


render () {
    this.el = document.createElement('div')
    this.el.style.cssText = `
        left: 0;
        top: 0;
        transform: translate(${this.x}px, ${this.y}px);
    `
    document.body.appendChild(this.el)
}


move () {
    // ...
    // this.el.style.left = this.x + 'px'
    // this.el.style.top = this.y + 'px'
    this.el.style.transform = `translate(${this.x}px, ${this.y}px)`
}


当然,最好的方式是用canvas来画。


最终效果:


image.png


下雨&雨夹雪


下完雪,接下来顺便下个雨,雨和雪差不多,都是从天上掉下来,但是雨的速度更快,通常也不会左右摇摆什么的,方向也基本是一致的,先来修改一下样式:


setStyle () {
  this.el.style.cssText = `
    // ...
    width: 1px;
    // ...
  `
}


很简单,只要把宽度写死为1就行了:


image.png


接下来把摇摆去掉:


move () {
  this.x += this.sx
  this.y += this.sy
  // ...
}


效果如下:


image.png


可以发现雨是竖着在水平移动,显然是不行的,需要让它倾斜一定的角度,和运动方向保持一致,这个也很简单,算一下斜率,水平速度除以垂直速度:


move () {
  // ...
  this.el.style.transform = `translate(${this.x}px, ${this.y}px) ${this.getRotate(this.sy, this.sx)}`
}
getRotate(sy, sx) {
  return `rotate(${sx === 0 ? 0 : (90 + Math.atan(sy / sx) * (180 / Math.PI))}deg)`
}


因为tan(θ)=sy/sx,θ=Math.atan(sy / sx),因为雨的线段默认是从上到下垂直的,θ是代表和水平方向上的夹角,所以需要先旋转90度,再旋转夹角的度数,最后弧度转角度的公式为:角度=弧度*(180/π)。


image.png


雨和雪都实现了,让它们一起出来,就是雨夹雪了:


image.png


根据天气下雪


把上面的代码放到网站上就有下雪的效果了,另外也可以使用天气厂商的api,根据实时天气来下雪或者下雨,再实现一下太阳、乌云等效果,一个沉浸式天气就完成了,有兴趣的可自行实践。


完整代码在github.com/wanglin2/sn…。



相关文章
|
移动开发 资源调度 JavaScript
夹吃灰,推荐:实现 SVG 动画的 5 个 JavaScript 库~
现如今,SVG 已经广泛应用于 Web 开发当中,可缩放而不失真(矢量图形),就是它的最大优势! 但是,你知道 SVG 除了可以被用作于静态图片,还可以应用于 SVG 动画吗? 本篇带来实现 SVG 动画的 5 个 JavaScript 库!
1692 0
|
2月前
|
存储 人工智能 Java
Spring AI 2.1 重量级更新!Java开发智能体大增强!
Spring AI 2.1.0-RC1重磅更新,Java开发智能体史诗级增强! 引入Human-in-the-Loop工具调用确认机制、引入全新的会话记忆(Session)会话自动压缩机制。
|
4月前
|
人工智能 弹性计算 运维
2026阿里云无影云电脑价格表:个人版/企业版收费、免费试用、APP下载教程
阿里云无影云电脑官网提供个人版(14.9元/月起,适配办公/游戏/AI)与企业版(199元/年起,支持批量管理、GPU图形型)双版本;含APP全端下载、新用户免费试用及Club中心代金券领取入口。阿里云无影云电脑官网:https://t.aliyun.com/U/4fqTBa
|
4月前
|
机器学习/深度学习 人工智能 自然语言处理
AI测试开发实习月薪6万起步,传统测试岗Offer跌破20万——2026届,选错方向毁三年
2026年测试行业正经历结构性裂变:AI测试开发实习月薪6万起,传统功能测试岗薪资跌破20万;全栈测开需求暴增340%,手工测试岗位锐减47%。差距不在能力,而在方向——AI测试聚焦模型评估、Agent验证与数据工程,是“自动化剩余”高地;传统测试则面临70%替代率。选对赛道,才是破局关键。
|
5月前
|
域名解析 弹性计算 网络安全
从零开始:阿里云服务器购买+配置+建站全流程教程
搭建个人或小型网站,阿里云ECS是稳定可靠的选择,从服务器购买、环境配置到网站部署,全程可按标准化流程完成,无需深厚技术基础。以下从前期准备、服务器购买、初始化配置、运行环境搭建、网站部署、域名解析与备案六大环节,详细拆解全流程,确保新手也能顺利完成网站上线。
1389 1
|
人工智能 开发框架 自然语言处理
企业级AI搜索解决方案:阿里云AI搜索开放平台
本文介绍了 阿里云 AI 搜索开放平台作提供丰富的 AI 搜索组件化服务,兼容主流开发框架 LangChain和 LlamaIndex,支持搜索专属大模型、百炼等大模型服务,以及 Elasticsearch、Havenask 等开源引擎。用户可灵活调用多模态数据解析、大语言模型、效果测评等数十个服务,实现智能搜索、检索增强生成(RAG)、多模态搜索等场景的搭建。
1709 0
|
JSON 监控 API
淘宝/天猫:使用订单查询API实时追踪包裹状态,自动推送物流通知至用户
在淘宝/天猫平台,通过集成订单查询API实现物流状态实时监控,结合定时轮询与自动推送通知功能,可有效减少用户频繁刷新页面,提升购物体验。本文详解API调用原理、状态判断及Python代码实现,助力开发者构建高效、智能的物流通知系统。
1572 0
|
人工智能 小程序 API
【一步步开发AI运动APP】四、使用相机组件抽帧
本文介绍了如何使用`ai-camera`组件开发AI运动APP,助力开发者深耕AI运动领域。`ai-camera`是专为AI运动场景设计的相机组件,支持多平台,提供更强的抽帧处理能力和API。文章详细讲解了获取相机上下文、执行抽帧操作以及将帧保存到相册的功能实现,并附有代码示例。无论是AI运动APP还是其他场景,该组件都能满足预览、拍照、抽帧等需求。下篇将聚焦人体识别检测,敬请期待!
|
弹性计算 安全 数据安全/隐私保护
阿里云ECS服务器被植入挖矿木马解决过程分享
阿里云ECS服务器是目前很多网站我们在使用的,但是如果安全做的不够好,有时候就会被植入木马,例如我们有时候会收到阿里云的短信提醒,提醒服务器存在挖矿进程,请立即处理的安全告警。 出现这种情况往往网站都无法正常的打开,卡的连服务器SSH远程连接都进不去,给我们造成了很大的影响。
12215 0