jsで雪を降らせるデモ「ソースあり」

 

環境

  • css
  • html
  • javascript
  • 四季
  • アニメーション
  • snow

実行

on.gif

デモ

ソース

GitHub

html

index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="UTF-8">
</head>


<body>
<script src="index.js"></script>
<div id="snow">
<h1>雪!</h1>
</div>
</body>
</html>

css

style.css
body{font-family:Helvetica,Arial,Sans-Serif;font-size:150px;color:#fff;background:#000;}
#snow {
    overflow: hidden;
    position: absolute;
    top: 0;
    left: 0;
    width: 1400px;
    height: 600px;
    background:-webkit-linear-gradient(top,#666,#111);
    background:-moz-linear-gradient(top,#666,#111);
    background:-o-linear-gradient(top,#666,#111);
    background:linear-gradient(top,#666,#111);
}
#snow div {
    position: absolute;
    text-align: center;
    height: 1em;
    width: 1em;
    line-height: 1em;
    color:transparent;
    top:-50px;left:0;
    -webkit-transition:all 10s;
    -webkit-transform:translate3d(0,0,0) rotate(0);
    -webkit-transition-timing-function:ease-in; 
}
#stage{display:none}

javascript

index.js
#javascript

// particle init
function Snowflake(options){
    options=options||{};
    this.vars={};
    var presets={posx:0,posy:0,posz:0,size:1,velx:0,vely:0,blur:1,gravity:0.1,spin:10,rotation:0,c:'❆'};
    for(var key in presets){this.vars[key]=(typeof options[key]==='undefined')?presets[key]:options[key];}
}
// particle render
Snowflake.prototype.render=function(){
    this.el.style.setProperty('-webkit-transform','translate3d('+this.vars.velx+'px,600px,0px) rotate('+this.vars.rotation+'deg)');
};
// launch particle
Snowflake.prototype.inject=function(parent){
    this.el=document.createElement('div');
    this.el.innerHTML=this.vars.c;
    var focusz=200;
    var distance=focusz-this.vars.posz;
    if(distance<0)distance*=-1;
    this.vars.blur=parseInt(distance/50);
    var st=this.el.style;
    st.fontSize=this.vars.size+'px';
    st.left=this.vars.posx+'px';
    st.textShadow='white 0 0 '+this.vars.blur+'px';
    parent.appendChild(this.el);
};
// super duper randomize algorithms (I wish)
function rndF(max){return Math.random(new Date().getTime())*max;}
function rndI(max){return parseInt(rndF(max));}



// use the library
function spawnFlake(){
    var flake=new Snowflake({
    posx:rndI(1400),
    posz:rndI(500),
    size:2+rndI(50),
    velx:-50+rndI(100),
    vely:10,
    rotation:-500+rndI(1000),
    c:'❆❄✱✶'[rndI(4)]
    });
    flake.inject(document.getElementById('snow'));
    setTimeout(function(){flake.render()}, 50);
}
setInterval(spawnFlake, 20);