HTML5+CSS3+JS实现满屏下雪效果
效果图:全部代码:<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"/><title>snow</title><style>.snow {position: absolute;background: url(img/snow.png);.
·
效果图:
全部代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>snow</title>
<style>
.snow {
position: absolute;
background: url(img/snow.png);
background-size: 100% 100%;
margin: auto;
/* 雪的样式 */
}
#container {
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
/* 设置容器背景为黑色*/
background: black;
}
#flower {
/* 画布容器雪花都在这里面*/
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
</style>
<script type="text/javascript">
const list = [];//用来装雪花的集合
//网页加载好之后会自动执行这个方法
window.onload = function () {
setInterval("run()", 10);//执行这个方法之后开始下雪
//参数1:方法名 参数2:间隔时间单位ms
//意思是每隔10ms执行一次run()方法
}
function newXue() { //创建一个雪花
const v = {};//创建一个对象
v.wh = Math.random() * 20 + 15;//wh代表雪花的宽高
const number = window.innerWidth / (window.innerWidth + window.innerHeight);
//number=概率的拼音;概率=浏览器宽度/(浏览器宽度+浏览器高度)
//假设你浏览器是1920*1080的那number就是0.64
//然后 雪花出现的位置有64%是在屏幕上边,36%是在屏幕右边
if (Math.random() < number) {
//在屏幕上方创建雪花 设置xy坐标
v.x = Math.random() * window.innerWidth;
v.y = -v.wh;
} else {
//在屏幕右方创建雪花 设置xy坐标
v.x = window.innerWidth;
v.y = Math.random() * window.innerHeight;
}
// 雪花的x轴移动速度
v.sdx = Math.random() + 0.3;
// 雪花的y轴移动速度
v.sdy = Math.random() + 1;
// 为每个雪花创建一个div,该div是用来显示雪花的
v.div = document.createElement("div");
// 设置div的类选择器
v.div.className = "snow";
// 设置div的位置
v.div.style.width = v.wh + "px";
v.div.style.height = v.wh + "px";
// 把div添加到画布flower容器里
document.getElementById("flower").appendChild(v.div);
// 雪花添加到集合
list.push(v);
}
const loader = 10;
let load = 0;
function run() {
load++;
// load === loader时创建一个雪花
if (load === loader) {
// 该方法每10ms执行一次,每执行10次这个方法就创建一个雪花
newXue();
load = 0;
}
// 雪花的移动,遍历list集合
for (let i = 0; i < list.length; i++) {
let v = list[i];
// 简单的坐标计算
v.x -= v.sdx;
v.y += v.sdy;
v.div.style.left = v.x + "px";
v.div.style.top = v.y + "px";
// 雪花飘出可视范围之后删除雪花
if (v.x + v.wh < 0 || v.y > window.innerHeight) {
// 从list删除雪花
list.splice(i, 1);
// 删除div
document.getElementById("flower").removeChild(v.div);
}
}
}
</script>
</head>
<body>
<div id="container"></div>
<div id="flower"></div>
</body>
</html>
素材:
项目下载地址:点我下载源码与素材
更多推荐
已为社区贡献5条内容
所有评论(0)