JSex2:小圓球動畫

【範例結果】

※源自codePen 由ES6 改為 JS

See the Pen Random Responsive balls in the background by Nash Vail (@nashvail) on CodePen.


一、CSS美化

  <style>
    body{
      overflow: hidden;
    }
    .ball {
      position: absolute;
      border-radius: 100%;
      opacity: 0.7;
    }
  </style>

二、JS設定

(1) 利用【for循環】、【push()方法】、

    var colors = ["#3CC157", "#2AA7FF", "#1B1B1B", "#FCBC0F", "#F85F36"];
    var numBalls = 50;
    var balls = [];

    for (var i = 0; i < numBalls; i++) {
      var ball = document.createElement("div");
      ball.classList.add("ball");
      ball.style.background = colors[Math.floor(Math.random() * colors.length)];
      ball.style.left = Math.floor(Math.random() * 100) + 'vw';
      ball.style.top = Math.floor(Math.random() * 100) + 'vh';
      ball.style.transform = 'scale(' + Math.random() + ')';
      ball.style.width = Math.random() + 'em';
      ball.style.height = ball.style.width;

      balls.push(ball);
      document.body.append(ball);
      console.log(ball);
    }

(2)JS 【forEach()(1)】、 【forEach()(2)】、【Element.animate()(1)】、【Element.animate()(2)

    balls.forEach(ballAn);

    function ballAn (el,i) {
      var to = {
        x: Math.random() * (i % 2 == 0 ? -12 : 12),
        y: Math.random() * 12
      };

      var anim = el.animate(
        [
          { transform: "translate(0, 0)" },
          { transform: 'translate('+to.x+'rem, '+to.y+'rem' }
        ],
        {
          duration: (Math.random() + 1) * 2000, // random duration
          direction: "alternate",
          fill: "both",
          iterations: Infinity,
          easing: "ease-in-out"
        }
      );
    }

備註:其他參考來源

(1)【JavaScript 陣列處理方法 [filter(), find(), forEach(), map(), every(), some(), reduce()]

(2) 【ES6豐富的forEach循環array和map

(3)【The for Loop vs. forEach in JavaScript

(4)【在 JavaScript 棄用 For 迴圈,擁抱 Reduce、ForEach、Filter、Map