好好学习 ,天天向上。Are you ready?
话不多说,代码奉上!
css部分:(雪花图片 自行寻找)
.snow
{
width: 80px;
height: 84px;
background-image: url("img/snow.png");
background-size: 100% 100%;
position: absolute;
}
js部分:
class Snow{
constructor(){
this.snow=null;
this.bool=true;
this.deg=0;
this.s=Math.random()*0.2+0.1;
}
createSnow(x,y){
if(!this.snow){
this.snow=document.createElement("div");
}
this.snow.className="snow";
this.snow.style.opacity="1";
this.snow.style.transform=`rotate(${this.deg}deg) scale(${this.s},${this.s})`;
this.snow.style.left=x-this.snow.offsetWidth/2+"px";
this.snow.style.top=y+"px";
return this.snow;
}
update(){
if(!this.bool) return;
this.deg+=3;
this.snow.style.transform=`rotate(${this.deg}deg) scale(${this.s},${this.s})`;
this.snow.style.opacity=Number(this.snow.style.opacity)-0.002;
this.snow.style.top=this.snow.offsetTop+0.5+"px";
if(this.s>0.2){
this.snow.style.left=this.snow.offsetLeft+0.5+"px";
}else{
this.snow.style.left=this.snow.offsetLeft-0.6+"px";
}
if(Number(this.snow.style.opacity)<=0){
this.bool=false;
}
}
}
let arr=[];
let time=3;
document.documentElement.style.overflow="hidden";
animation();
function animation() {
requestAnimationFrame(animation);
let list=[];
for(let i=0;i<arr.length;i++){
arr[i].update();
if(!arr[i].bool){
arr[i].snow.remove();
arr[i]=null;
}else{
list.push(arr[i]);
}
}
arr=list.concat();
list=null;
time--;
if(time>0) return;
time=Math.floor(Math.random()*8);
let snow=new Snow();
document.body.appendChild(snow.createSnow(Math.random()*document.documentElement.clientWidth,-50));
arr.push(snow);
}