MON NEWS

CSSの新しい機能random関数でできること


cssが多様なアニメーションも可能にした

あたらしいcssのrandom関数はできることが多い。javascriptの補助も少し必要だが、下記のようなアニメーションも比較的簡単に可能になった。これまでなら難しいjavascriptが必要だったものが、cssの記述によってほとんどができてしまう。新しいバージョンであればChrome、Safari、Edge、FireFoxのブラウザでの表示ができる。

CSSでのアニメーション

CSS random()

サンプルコード

HTML
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>CSS random() 加速しながら飛び出すカラフルな玉</title>
<style>
  body {
    margin: 0;
    background-color: #1a1a2e;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
  }

  /* 幅1000px・高さ600pxの画面エリア */
  .screen {
    position: relative;
    width: 1000px;
    height: 600px;
    overflow: hidden;
    background-color: #16213e;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  /* 中央の大きなゴシック体文字 */
  .title {
    position: relative;
    z-index: 10;
    margin: 0;
    color: #ffffff;
    font-size: 64px;
    font-weight: 900;
    font-family: "Hiragino Kaku Gothic ProN", "Hiragino Sans", "Yu Gothic", "Meiryo", sans-serif;
    letter-spacing: 0.05em;
    text-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
    pointer-events: none;
  }

  /* 飛び出す玉のスタイル */
  .ball {
    position: absolute;
    left: 50%;
    top: 50%;
    z-index: 1;
    border-radius: 50%;

    /* 基準サイズ */
    width: random(15px, 35px);
    aspect-ratio: 1;

    /* 色(HSLの色相)と周囲のぼかし */
    background-color: hsl(random(0, 360), 85%, 65%);
    filter: blur(random(1px, 4px));

    /* 360度ランダムな角度と画面外(700px先)の座標 */
    --angle: random(0deg, 360deg);
    --tx: calc(cos(var(--angle)) * 700px);
    --ty: calc(sin(var(--angle)) * 700px);

    /* 発生直後はゆっくり動き、画面外に近づくにつれて急加速する指定 */
    animation: flyOut random(3s, 6s) cubic-bezier(0.7, 0, 0.84, 0) forwards;
  }

  /* 画面の外に出るまで不透明(opacity: 1)のまま飛び出すアニメーション */
  @keyframes flyOut {
    0% {
      transform: translate(-50%, -50%) scale(0.05);
      opacity: 0;
    }
    15% {
      opacity: 1;
    }
    100% {
      transform: translate(calc(-50% + var(--tx)), calc(-50% + var(--ty))) scale(3.5);
      opacity: 1;
    }
  }
</style>
</head>
<body>

  <div class="screen" id="screen">
    <h1 class="title">CSS random()</h1>
  </div>

  <script>
    const screen = document.getElementById('screen');

    setInterval(() => {
      const ball = document.createElement('div');
      ball.className = 'ball';
      screen.appendChild(ball);

      ball.addEventListener('animationend', () => {
        ball.remove();
      });
    }, 100);
  </script>

</body>
</html>