在JS中制作雪的最佳方式?

时间:2016-12-19 16:54:45

标签: javascript animation

对于一个学校项目,我需要使用JavaScript创建一张圣诞卡,我无法在不同的时间创建雪花,并且使用与其他雪花不同的x值。

现在,我知道雪花在掉落时应该看起来如何,但我需要一些帮助来产生其余的雪。

下面是它看起来的样子:

    sy++;
    if(sy <= 400) {
        snowy = sy;
    } else {
        sy = 0;
    }

    sx++;
    if(sx < 400) {
        snowx1 = sx;
        snowx2 = sx + 1;
    } else {
        sx = 0;
    }

    ellipse(random(snowx1, snowx2), snowy, 10, 10);

如何在不更改random()部分的情况下获取以不同x值生成的特定动画?

1 个答案:

答案 0 :(得分:2)

新年快乐;)

&#13;
&#13;
var snow_intensity = 50; // smaller number = more snowflakes;

function Snowflake(){
  var snowflake = this;
  snowflake.x = (Math.random() * $(document).width());
  snowflake.size = (Math.random() * 35) + 10;
  snowflake.opacity = Math.random();
  snowflake.body = $("<em class='snowflake'>*</em>");
  snowflake.body.css({'font-size': this.size + 'px', 'left': this.x +'px', opacity: this.opacity });
  snowflake.fall = function(){
    var that = this;
    var $snowflake = this.body;
    var swing_direction = 1;
    var swing_wave = Math.random() * 100;
    var interval = setInterval(function(){
      $snowflake.css({left: that.x + (swing_direction * swing_wave)});
      swing_direction = - swing_direction;
    }, 1000);
    var speed = (Math.random() * 3000) + 3000;
    $snowflake.animate({top: '100vh'}, speed, function(){
      clearInterval(interval);
      $snowflake.remove();
    });    
  }
  $('body').append(snowflake.body);
  snowflake.fall();
}

var snow = window.setInterval(function () {
   new Snowflake();
}, snow_intensity);

document.onkeypress = function () {
  window.clearInterval(snow);
};
&#13;
body {background: CornflowerBlue;overflow:hidden;}
h1 {
  color:LightSkyBlue;
  text-align:center;
  opacity:.2;
}
.snowflake{
  position:absolute;
  top:-40px;
  transition: left 5s;
  opacity:1;
  color: #fff;
  -webkit-animation:spin 4s linear infinite;
  -moz-animation:spin 4s linear infinite;
  animation:spin 4s linear infinite;
}

@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h1>HAPPY NEW YEAR</h1>
&#13;
&#13;
&#13;