JS实现雪花飘飘
给大家分享一下,JS的雪花飘飘是如何实现的,我们先看一下实现的效果,如下图:
由于颜色问题,看起来并不清楚,抱歉,但是效果是很不错的!
下面是实现的源码,讲解也在源码里:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>js雪花飘飘</title>
<style type="text/css">
//@keyframes 设置动画的帧
@keyframes sn{
from{//表示开始时的变化
opacity:0;
bottom:100%;
}
60%{//表示达到动画60%的地方变化
opacity:1;
transform:rotate(720deg);//旋转720度
}
to{//到达底部的变化
bottom:0%;
opacity:0;//t透明度
transform:rotate(360deg);//旋转360度
}
}
.div2{position:fixed;}
.img{height:30px;position:absolute;
opacity:0;
animation:sn 5s;//引用动画的帧和设置动画时间
}
</style>
</head>
<body>
<div id="div1"></div>
<script type="text/javascript">
function snow(x,y,src)
{
var pare=document.createElement("div");
var img=document.createElement("img");
var div1=document.getElementById("div1");
pare.appendChild(img);
div1.appendChild(pare);
pare.className="div2";
img.className="img";
pare.style.left=x+"px";
pare.style.height=y+"px";
img.src=src;
setTimeout(function () {
div1.removeChild(pare);
},5000);
}
setInterval(function () {//每隔500毫秒执行一次
var x=Math.random()*window.innerWidth;
var y=Math.random()*window.innerHeight;
var src="雪花.png";
snow(x,y,src);
},500);
</script>
</body>
</html>