【问题标题】:How can I animate falling snowflakes in JS?如何在 JS 中为飘落的雪花制作动画?
【发布时间】:2016-12-19 16:54:44
【问题描述】:

对于一个学校项目,我需要使用 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 值生成的特定动画?

【问题讨论】:

    标签: javascript animation


    【解决方案1】:

    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);
    };
    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); } }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <h1>HAPPY NEW YEAR</h1>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-09
      • 2012-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      相关资源
      最近更新 更多