分享一个用js实现的简单的雪花效果,效果如下:
简单说明下,这里的雪花图标来自于iconfont阿里云矢量图标库,如何使用可以查看我之前发布的文章《vue项目如何引用阿里云矢量图标库》,用法都一样的;话不多说,直接开干。
HTML代码
<div class="content">
<div class="form-wrapper">
<button class="form" onclick="handleClear()">清除</button>
<button class="form" onclick="handleSnow()">小雪</button>
<button class="form" onclick="handleSnow(5, 10, 16, 300)">中雪</button>
<button class="form" onclick="handleSnow(6, 10, 14, 400)">暴雪</button>
</div>
<div class="wrapper" id="wrapper"></div>
</div>
css代码
*{
padding: 0;
margin: 0;
}
.content{
width: 100%;
height: 100vh;
position: relative;
background: url("static/bg.jpg") no-repeat;
}
.form-wrapper{
height: 80px;
top: 20px;
left: 20px;
position: absolute;
z-index: 1;
}
.form{
width: 150px;
font-size: 18px;
font-weight: bold;
color: #fff;
background: transparent;
cursor: pointer;
line-height: 40px;
border: 2px solid #fff;
margin: 0 5px;
}
.form:hover{
background-color: rgba(255,255,255, .2);
}
.wrapper{
height: 100%;
width: 100%;
position: relative;
background-repeat: no-repeat;
overflow: hidden;
}
.icon-xuehua{
color: #fff;
position: absolute;
}
js代码
const SNOW_NUM = 200;
const [MIN_SIZE, RANGE] = [16, 20];
const WIDTH = document.documentElement.clientWidth;
const HEIGHT = document.documentElement.clientHeight;
const wrapper = document.getElementById("wrapper");
const getRandom = (min = 16, range = 20) => Math.round(Math.random() * range + min);
function handleClear() {
wrapper.innerHTML = "";
}
function createSnow(step, min, range) {
const ele = document.createElement("span");
let [left, top] = [getRandom(0, WIDTH - (MIN_SIZE + RANGE)), getRandom(0, HEIGHT - (MIN_SIZE + RANGE))]
ele.className = "iconfont icon-xuehua";
ele.style.fontSize = `${getRandom(MIN_SIZE, RANGE)}px`;
ele.style.left = `${left}px`
ele.style.top = `${top}px`
wrapper.appendChild(ele)
setInterval(() => {
if (top >= HEIGHT - (MIN_SIZE + RANGE)) {
top = 0;
}
top = top + step;
ele.style.top = `${top}px`
}, getRandom(min, range))
}
function handleSnow(step = 4, min = 10, range = 20,num = SNOW_NUM) {
handleClear();
for(let i = 0; i < num; i ++) {
createSnow(step, min, range);
}
}
handleSnow();
基本原理就是通过定位,让元素随机定位到浏览器窗口中,利用定时器定时改变元素的top值,然后再对元素进行边界判断。
网友评论